简体   繁体   English

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

[英]Conversion of a UTC date/time string in C#

I need to convert the string "Fri Sep 11 00:00:00 GMT+04:00 2020" into a DateTime object 11.09.2011 . 我需要将字符串"Fri Sep 11 00:00:00 GMT+04:00 2020"转换为DateTime对象11.09.2011

When I use 我用的时候

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

result is equal to {9/10/2020 11:00:00 PM} . result等于{9/10/2020 11:00:00 PM}

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) ? 我如何修改代码,以便日期组件是11.09.2011 ,而不是 10.09.2011 (我只需要日期和不关心的时间)?

Parse into a DateTimeOffset instead, given that you've got an offset. 考虑到你一个偏移量,请将其解析为DateTimeOffset From the documentation of the zz specifier that you're using: 从您正在使用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. 使用DateTime值,“zz”自定义格式说明符表示本地操作系统的时区与UTC的签名偏移量,以小时为单位。 It does not reflect the value of an instance's DateTimeKind property. 它不反映实例的DateTimeKind属性的值。 For this reason, the "zz" format specifier is not recommended for use with DateTime values. 因此,建议不要将“zz”格式说明符与DateTime值一起使用。

So you'd end up with: 所以你最终得到:

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

From there, you can take the DateTime part, which will be midnight on September 11th. 从那里,你可以采取DateTime部分,这将是9月11日午夜。

If you want just a date, you could use my Noda Time project to create a LocalDate : 如果您想要一个日期,可以使用我的Noda Time项目来创建LocalDate

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

(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.) (我很乐意建议直接解析为OffsetDateTime ,但我们还没有得到支持。我们希望将它包含在1.2版本中。)

C# does not have a pure Date type. C#没有纯Date类型。
If you don't care about the time, just ignore that portion of the DateTime . 如果您不关心时间,只需忽略DateTime那一部分。

If you want the time to always be midnight, use the .Date property, which will return a DateTime with the same date but at midnight. 如果您希望时间始终为午夜,请使用.Date属性,该属性将返回具有相同日期但午夜的DateTime

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

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