且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在C#中的UTC日期/时间字符串转换

更新时间:2023-02-12 15:18:07

解析成的DateTimeOffset 代替,因为你已经的得到的偏移量。从 ZZ $ C $的文档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.)