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

匿名 (未验证) 提交于 2019-12-03 02:27:02

问题:

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.

回答1:

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.



回答2:

Try a format string like this:

"yyyy-MM-dd'T'hh:mm:ss%K" 

As you can see from the example, this parses better than what you specified (the duplicate hh:mm is probably screwing things up).

string input = "2015-07-09T08:38:49-07:00"; DateTime dt = DateTime.ParseExact(input, "yyyy-MM-dd'T'hh:mm:ss%K", System.Globalization.CultureInfo.InvariantCulture); Console.WriteLine(input); Console.WriteLine(dt.ToString()); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!