4

I've created a string extension method which will convert the specific string to DateTimeOffset. I executed the following method:

public static DateTimeOffset? ConvertToDateTimeOffset(this string text)
{
    DateTimeOffset date;

    if (DateTimeOffset.TryParse(text, out date))
    {
        return date;
    }
    else
    {
        return null;
    }
}

with this string:

"2010-05-10".ConvertToDateTimeOffset()

I want to get back the following result:

{2010. 05. 10. 0:00:00 +00:00}

But the actual result of my execution method call is (please, notice +02:00):

{2010. 05. 10. 0:00:00 +02:00}

How can I eliminate this time zone issue?

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
pbarna
  • 51
  • 1
  • 4

2 Answers2

8

If you want UTC, not local time you have to specify it manually with DateTimeStyles.AssumeUniversal:

... 
if (DateTimeOffset.TryParse(text, 
                            CultureInfo.InvariantCulture,
                            DateTimeStyles.AssumeUniversal, 
                            out date)) {
  ...
}
...

You can simplify the implementation (C# 7.0+) with out var:

public static DateTimeOffset? ConvertToDateTimeOffset2(this string text) {
  return DateTimeOffset.TryParse(text, 
                                 CultureInfo.InvariantCulture, 
                                 DateTimeStyles.AssumeUniversal, 
                                 out var date)
    ? date
    : (DateTimeOffset?) null;
}
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

Check this link.

I believe that you are looking for

   DateTimeOffset.TryParse(text, null, DateTimeStyles.AssumeUniversal, out date);

According to the documentation

Indicates that, if the input parameter lacks an <Offset> element, the UTC offset (00:00) should be provided.

Krik
  • 355
  • 4
  • 9