Parse a UTC date string to date in C#
c#, datetime, parsing, string
Solution
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.)
Problem
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