0

I have this DateTime as string: 2015-08-21T10:51:25.9495986+02:00

How can I parse this string date into a DateTime object?

I usually do this:

CultureInfo provider = CultureInfo.InvariantCulture;   

DateTime _date;

DateTime.TryParseExact("2015-05-12T12:00:00", "yyyy-MM-ddTHH:mm:ss", provider, DateTimeStyles.None, out _date))

But now the end of the DateTime contains +02:00. Never faced this format and I believe this has to do something with the Time Region right?

0

2 Answers 2

1

You can simply use the o specifier for the format

DateTime.TryParseExact("2015-08-21T10:51:25.9495986+02:00", "o", provider, DateTimeStyles.None, out _date);

This will provide you a local time, to convert to universal time you can use .ToUniversalTime()

Sign up to request clarification or add additional context in comments.

2 Comments

IMHO parsing to DateTime is not appropriate here. Because it might generate different results in different timezone machines. For example; I'm UTC+3 right now and your code generates 21.08.2015 11:51:25 on my machine but in Ideone, it generates 21.08.2015 08:51:25. That's why parsing DateTimeOffset can be a better approach in this case.
@SonerGönül I think you're probably right, albeit the OP was asking how to parse to a DateTime.
-1

Your answer is here: C# string to DateTime with timezone

But to help: "You should try using DateTimeOffset instead of the DateTime"

See the following example:

DateTimeOffset result = DateTimeOffset.Parse("2012-04-20 10:10:00+0200",CultureInfo.InvariantCulture);

3 Comments

If you found a dup you should just comment about it and when you have more rep you can just vote to close as a dup. No need to put it in an answer.
Thanks @juharr, I'll see if I have this sufficient rep to do this.
You need 3,000 to vote to close.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.