Walmikk
Walmikk

Reputation: 45

Convert JSON date to C# datetime variable

I want to convert my JSON formatted date to C# DateTime variable. Trying to convert it with Convert.ToDateTime

("2016-01-15T11:44:52-07:00")

is giving me this output

"1/16/2016 12:14:52 AM" enter image description here

I am not able to find out whether it is a correct output or not because my input date is 15 Jan 2016 but in output it is 16 Jan 2016.

How can I convert a JSON date value to a C# date value?

Upvotes: 0

Views: 4635

Answers (2)

Georg Patscheider
Georg Patscheider

Reputation: 9463

You seem to have problems with the time zones. Try parsing with DateTimeStyles.RoundtripKind

using System.Globalization;

var s1 = "2016-01-15T11:44:52-07:00";
var date = DateTime.Parse(s1, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind);

Upvotes: 0

Soner Gönül
Soner Gönül

Reputation: 98740

Looks like your current timezone is UTC +05:30 right now and that's why Convert.ToDateTime method adds those value to the result and generates 1/16/2016 00:14:52 as a value.

Since your string has an offset part, I would parse it to DateTimeOffset instead of Datetime.

var dto = DateTimeOffset.Parse("2016-01-15T11:44:52-07:00");

This will generate {15.01.2016 11:44:52 -07:00} as a DateTimeOffset.

enter image description here

But since you said this is related with Json, this technology should have some methods to parse it as well. It would be better to use those methods but I'm not familiar with JSON.

Upvotes: 6

Related Questions