Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse a UTC date string to date in C#

Simple question, I have this string:

string dateString = "7/12/2014 4:42:00 PM";

This is a date string and it's in the UTC timezone.

I need to convert it to a date, so I'm doing the following:

DateTimeOffset dateOffset;

DateTimeOffset.TryParse(dateString, out dateOffset);

DateTime date = dateOffset.UtcDateTime;

The problem:

When I'm parsing the string to date, the code is considering that the dateString is in the Local Timezone of the PC (+3 GMT), and not in the UTC timezone.

So I am getting the following the dateOffset = {7/12/2014 4:42:00 PM +03:00} and thus date = {7/12/2014 1:42:00 PM}

how can I tell him that the date string provided is in the UTC format and not in the local timezone format?

Thanks

like image 560
Y2theZ Avatar asked Jul 12 '14 17:07

Y2theZ


2 Answers

how can I tell him that the date string provided is in the UTC format and not in the local timezone format?

Specify a DateTimeStyles value of AssumeUniversal in the call. That tells the parsing code what to do. For example:

// null here means the thread's current culture - adjust it accordingly.
if (DateTimeOffset.TryParse(dateString, null, DateTimeStyles.AssumeUniversal,
                            out dateOffset))
{
    // Valid
}

You should always use the result of TryParse to tell whether or not it's successfully parsed.

If you know the format and the specific culture, I'd personally use DateTimeOffset.TryParseExact. (Well, to be honest I'd use my Noda Time project to start with, but that's a different matter.)

like image 138
Jon Skeet Avatar answered Sep 22 '22 14:09

Jon Skeet


There is another overload of DateTimeOffset.TryParse

DateTimeOffset.TryParse Method (String, IFormatProvider, DateTimeStyles, DateTimeOffset)

which allows you specify DateTimeStyles. One of the DateTimeStyles is AssumeUniversal, which is what you're looking for:

If no time zone is specified in the parsed string, the string is assumed to denote a UTC. This value cannot be used with AssumeLocal or RoundtripKind.

like image 43
MarcinJuraszek Avatar answered Sep 24 '22 14:09

MarcinJuraszek