imGreg
imGreg

Reputation: 900

Convert string to datetime UTC

I have this string "Sun Aug 02 2015 00:15:47 GMT+0000 (UTC)"

I created this much of the datetime format "ddd MMM dd yyyy HH:mm:ss"

Now im not sure what to do with the ending part of that datetime string. Im not sure if the string I have is a standard format for UTC that can be easily converted or if its a custom format.

Nonetheless, I want to turn that string datetime into a datetime object.

Upvotes: 1

Views: 8928

Answers (2)

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241525

I would consider one of these two approaches:

string str = "Sun Aug 02 2015 00:15:47 GMT+00:00 (UTC)";
str = str.Substring(0, str.IndexOf('(') - 1);
DateTime dt = DateTime.ParseExact(str, "ddd MMM dd yyyy HH:mm:ss 'GMT'K",
    CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);

or

string str = "Sun Aug 02 2015 00:15:47 GMT+00:00 (UTC)";
str = str.Substring(0, str.IndexOf('(') - 1);
DateTimeOffset dto = DateTimeOffset.ParseExact(str, "ddd MMM dd yyyy HH:mm:ss 'GMT'K",
    CultureInfo.InvariantCulture);

In either example, we assume that the part in parenthesis is irrelevant. This may be important if your input can vary with different time zones.

In the first example, we assume that you want the output to always be a UTC based DateTime. The input offset could vary, but the output will always be adjusted to Coordinated Universal Time, and will have DateTimKind.Utc.

In the second example, we assume that you want the output to match exactly what was provided in the input. To do this, the output needs to be a DateTimeOffset type. Otherwise, you wouldn't be able to track offsets that didn't exactly match UTC or your own local time zone.

I prefer the second option. If you need a DateTime, you can always get one by calling the .DateTime, .UtcDateTime, or .LocalDateTime properties of the resulting DateTimeOffset.

Upvotes: 2

EZI
EZI

Reputation: 15354

string str = "Sun Aug 02 2015 00:15:47 GMT+0000 (UTC)";
var dt = DateTime.ParseExact(str, "ddd MMM dd yyyy HH:mm:ss \"GMT\"zzzz \"(UTC)\"", CultureInfo.InvariantCulture);

Upvotes: 3

Related Questions