Conversion of a UTC date/time string in C#

可紊 提交于 2019-12-01 17:58:14

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

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.

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.

If you want just a date, you could use my Noda Time project to create a 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.)

C# does not have a pure Date type.
If you don't care about the time, just ignore that portion of the 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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!