简体   繁体   English

C#解析日期时间与时区

[英]c# parse date time with timezone

How can we parse date time with time zone. 我们如何解析带时区的日期时间。

<TIMESTAMP_UTC>20180523160000</TIMESTAMP_UTC>
<TIMEZONE>UTC+8</TIMEZONE>

this should convert as in 2018-05-24 00:00:00. 这应转换为2018-05-24 00:00:00。 I tried couple of things but could not succeed. 我尝试了几件事,但未能成功。 I tried the below command but it throws an error. 我尝试了以下命令,但抛出错误。

DateTime.ParseExact("20180523160000+08:00", "yyyyMMddHHmmssZhhmm", System.Globalization.CultureInfo.InvariantCulture)

Do you know how we can parse this with DateTime Parse methods. 您知道我们如何使用DateTime Parse方法进行解析。

您需要使用DateTimeOffset.ParExact

var date = DateTimeOffset.ParseExact("20180523160000+08:00", "yyyyMMddHHmmsszzz", CultureInfo.InvariantCulture);

Try using DateTimeOffset.Parse() instead of DateTime.Parse() as DateTimeOffset stores timezone info. 尝试使用DateTimeOffset.Parse()而不是DateTime.Parse()因为DateTimeOffset存储时区信息。

You can refer to the following MSDN link for more details: 您可以参考以下MSDN链接以获取更多详细信息:

https://msdn.microsoft.com/en-us/library/bb351654(v=vs.110).aspx https://msdn.microsoft.com/en-us/library/bb351654(v=vs.110).aspx

You could invert the sign of your timezone and then parse it with 您可以反转时区的符号,然后使用

var dateTime = DateTime.ParseExact(
    "20180523160000UTC-8",
    "yyyyMMddHHmmssUTCz",
    CultureInfo.InvariantCulture);

But if this is a good approach is probably questionable. 但是,如果这是一种好方法,则可能会令人怀疑。

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

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