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?
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With