How do I create a DateTime object given UTC time and date?

I have date and time strings already in UTC. I need to use those strings to create a DateTime object.

This is the code I'm using. The problem is the time gets converted and my UTC time on the datetime object is no longer correct. I'm giving UTC values so they shouldn't get converted again.

string format = $"{dateFormat}_{timeFormat}";
string value = $"{dateValue}_{timeValue}";

var x = DateTimeOffset.ParseExact(value, format, CultureInfo.CurrentCulture).UtcDateTime;

where dateFormat = "ddMMyy", timeFormat = "HHmmss", dateValue = "191194" and timeValue = "225446".

Jon Skeet
people
quotationmark

D Stanley's answer certainly works, but is slightly more complex than you need - if you want a DateTime as the result, you don't need to use DateTimeOffset at all, as DateTime.ParseExact handles DateTimeStyles.AssumeUniversal as well, although you need to specify AdjustToUniversal so that the result is in UTC. (Otherwise it's adjusted to the local time zone automatically - and unhelpfully, IMO, but that's a battle for another day.)

var x = DateTime.ParseExact(
     value, 
     format, 
     CultureInfo.CurrentCulture,  
     DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);

Sample code (that revealed to me the need for DateTimeStyles.AdjustToUniversal):

using System;
using System.Globalization;

class Test
{
    static void Main(string[] args)
    {
        string text = "2015-06-10 20:52:13";        
        string format = "yyyy-MM-dd HH:mm:ss";
        var dateTime = DateTime.ParseExact(
            text,
            format, 
            CultureInfo.InvariantCulture,
            DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
        Console.WriteLine(dateTime);  // 10/06/2015 20:52:13 on my box
        Console.WriteLine(dateTime.Kind); // Utc
    }
}

I'd be careful using CultureInfo.CurrentCulture, by the way - bare in mind the fact that it can affect the calendar system in use as well as format strings etc.

(As a side-note of course, I'd recommend using my Noda Time library instead. In this case I'd probably suggest parsing your time using a LocalTimeFormat, your date using a LocalDateFormat, then adding the results together to get a LocalDateTime that you could then convert to a ZonedDateTime using UTC. Or you could use your existing approach to create a ZonedDateTimePattern or InstantPattern, of course.)

people

See more on this question at Stackoverflow