Y2theZ
Y2theZ

Reputation: 10412

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

Upvotes: 12

Views: 6942

Answers (3)

Wint
Wint

Reputation: 2298

Don't know how .Net API provides, but I guess you could probably use ISO8601 format to indicate a UTC timezone before parsing, i.e, first translate 7/12/2014 4:42:00 PM into something 2014-07-02T16:42:00Z, then use try parse using DateTimeOffset

Upvotes: 1

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

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.

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1500465

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.)

Upvotes: 25

Related Questions