简体   繁体   English

解析带时区的日期,跳过时区

[英]Parse date with time zone, skip timezone

I try to parse date from string which contains time zone information. 我尝试从包含时区信息的字符串中解析日期。 Input string is 2014-12-17T08:05:39+00:00 . 输入字符串是2014-12-17T08:05:39+00:00

I use DateTime.Parse() method which return me 2014-12-17 09:05:39 (one hour was added). 我使用DateTime.Parse()方法返回2014-12-17 09:05:39 (增加了一个小时)。 I live in UTC+1:00 (Warsaw) , so .NET adopt this date to my local time. 我住在UTC+1:00 (Warsaw) ,所以.NET将这个日期设为本地时间。

My question is how to use the parse method while skipping time zone, for example for 2014-12-17T08:05:39+00:00 I want to get 2014-12-17 08:05:39 . 我的问题是如何在跳过时区时使用解析方法,例如对于2014-12-17T08:05:39+00:00我想获取2014-12-17 08:05:39

I would recommend parsing it as a DateTimeOffset instead of as a DateTime . 我建议将其解析为DateTimeOffset而不是DateTime You can then get the DateTime out of that, but it separates the "parsing the data you've been given" step from the "only using the bits I want from that" step. 然后,您可以从中获取DateTime ,但它将“解析已提供的数据”步骤与“仅使用我想要的那个位”步骤分开。

It's possible that there are ways to make DateTime.Parse behave the way you want using DateTimeStyles - and I'm surprised it's converting to a "local" kind automatically anyway - but using DateTimeOffset will make it clearer. 这有可能是有办法让DateTime.Parse表现你想使用的方式DateTimeStyles -我很惊讶它转换为“本地”之类的自动反正-但使用DateTimeOffset将使其更清晰。

(Of course I'd really recommend using Noda Time instead, parsing to an OffsetDateTime and then getting the LocalDateTime out of that, but that's a different matter...) (当然,我真的建议您使用Noda Time代替,解析为OffsetDateTime然后OffsetDateTime获取LocalDateTime ,但这是另一回事...)

If you remove the part specifying time zone in input string then it parses directly without adjusting to local time. 如果您删除了输入字符串中指定时区的部分,则它将直接解析而无需调整本地时间。 The date.Kind is then Unspecified . date.Kind然后Unspecified

var input = "2014-12-17T08:05:39";
var date = DateTime.Parse(fixedInput);

Although this works you might want to have a look on NodaTime as well. 尽管此方法可行,但您可能还希望了解NodaTime。

You should try using DateTimeOffset instead of the DateTime 您应该尝试使用DateTimeOffset而不是DateTime

DateTimeOffset result = DateTimeOffset.Parse("2014-12-17T08:05:39+00:00", CultureInfo.InvariantCulture);

it gives you : 12/17/2014 8:05:39 AM +00:00 它给你: 12/17/2014 8:05:39 AM +00:00

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM