Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert datetime string with this format: (yyyy-MM-dd'T'hh:mm:ss-zzz)

I am receiving a JSON string that contains a date that looks like this: 2015-07-09T08:38:49-07:00 where the last part is the timezone. Is there a standard way to convert this to a DateTimeOffset?

Here is what I have so far:

var olu = JsonConvert.DeserializeObject<OneLoginUser>(jToken.ToString(), new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd'T'HH:mm:sszzz" });

This doesn't deserialize any of the dates. I've tried using -Z and hh:mm for the timezone data, but I can't seem to deserialize any of the dates.

For reference, this is from OneLogin, a SSO provider. Here's a link to the user documentation. Notice the bit about the dates at the top.

like image 636
joelforsyth Avatar asked Nov 23 '15 19:11

joelforsyth


People also ask

What time zone does SimpleDateFormat use?

Since it does not hold any timezone information, its toString function applies the JVM's timezone to return a String in the format, EEE MMM dd HH:mm:ss zzz yyyy , derived from this milliseconds value.

What is SimpleDateFormat?

SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. It allows for formatting (date -> text), parsing (text -> date), and normalization. SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting.


1 Answers

That is a standard ISO 8601 extended format timestamp with offset, also covered by RFC 3339. There's nothing special about it.

DateTimeOffset.Parse("2015-07-09T08:38:49-07:00")

Or

DateTimeOffset.ParseExact("2015-07-09T08:38:49-07:00", "yyyy-MM-dd'T'HH:mm:sszzz",
                                                       CultureInfo.InvariantCulture)

With JSON.Net, the defaults should work well. No need to specify anything special.

JsonConvert.DeserializeObject<DateTimeOffset>("\"2015-07-09T08:38:49-07:00\"")

The fiddle Brian posted in the question comments shows that it works when deserializing a larger object. If you're still not getting it to work, perhaps you could edit your question to show the specific JSON you're trying to deserialize and the object structure you're putting it into.

One thing I noticed about your code, you show the json coming from jToken.ToString(), so somewhere you must have previously parsed using JObject.Parse. It's a little strange to do that, just to convert back to json and deserialize. Either go directly from the json string to the entity using JsonConvert.DeserializeObject, or use jToken.ToObject<OneLoginUser>() if you're already starting with jToken for some other reason. No need to mix both APIs, and it's possible you're loosing the date/time information in the process depending on what your settings are.

like image 188
Matt Johnson-Pint Avatar answered Sep 25 '22 09:09

Matt Johnson-Pint