在C#中的UTC日期/时间字符串转换 [英] Conversion of a UTC date/time string in C#

查看:569
本文介绍了在C#中的UTC日期/时间字符串转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将字符串转换周五09月11日00:00:00 GMT + 04:00 2020年的DateTime 对象 2011年9月11日

I need to convert the string "Fri Sep 11 00:00:00 GMT+04:00 2020" into a DateTime object 11.09.2011.

当我使用

DateTime result;
DateTime.TryParseExact(MyString, "ddd MMM dd HH:mm:ss 'GMT'zzz yyyy", 
    CultureInfo.InvariantCulture, DateTimeStyles.None, out result);



结果等于 {2020年9月10日下午11时00分零零秒}

我如何修改代码,以便日期组件 2011年9月11日不可以 2011年9月10日(我只需要日期和唐关于时间t照顾)?

How can I modify the code so that the date component is 11.09.2011 and not 10.09.2011 (I only need the date and don't care about the time) ?

推荐答案

解析成的DateTimeOffset 代替,因为你已经的得到的偏移量。从 ZZ 文档C>您使用说明:

Parse into a DateTimeOffset instead, given that you've got an offset. From the documentation of the zz specifier that you're using:

通过DateTime值的ZZ自定义格式说明符代表签署偏移从UTC本地操作系统的时区,以小时计算。它不反映一个实例的DateTimeKind属性的值。由于这个原因,不推荐使用DateTime值使用ZZ格式说明

With DateTime values, the "zz" custom format specifier represents the signed offset of the local operating system's time zone from UTC, measured in hours. It does not reflect the value of an instance's DateTimeKind property. For this reason, the "zz" format specifier is not recommended for use with DateTime values.

所以,你会结束:

DateTimeOffset result;
bool success = DateTimeOffset.TryParseExact
         (text, "ddd MMM dd HH:mm:ss 'GMT'zzz yyyy", 
          CultureInfo.InvariantCulture, DateTimeStyles.None, out result);



从那里,你可以采取的DateTime 份,这将是9月11日午夜

From there, you can take the DateTime part, which will be midnight on September 11th.

如果你想的只是的日期,你可以用我的野田佳彦时间项目,以创建一个 LOCALDATE

If you want just a date, you could use my Noda Time project to create a LocalDate:

LocalDate = OffsetDateTime.FromDateTimeOffset(result).LocalDateTime.Date;



(我很想建议直接向解析 OffsetDateTime ,但我们没有得到这种支持呢。我们希望将其包含在1.2版本)。

(I'd love to suggest parsing directly to OffsetDateTime, but we haven't got support for that yet. We're hoping to include it in version 1.2.)

这篇关于在C#中的UTC日期/时间字符串转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆