解析日期时间
我有一个日期时间作为字符串,例如。 “2010-08-02”,我尝试使用以下代码片段将其转换为 UTC
DateTime.ParseExact("2010-08-02Z", "yyyy-MM-ddZ", CultureInfo.InvariantCulture)
当我打印到控制台时,我得到以下内容:8/1/2010 5:00:00 PM。 日期显示为我尝试解析的日期之前的日期是否有原因?我可以添加一天以提前到原始日期,但我想看看我在格式中是否做错了什么导致了这种情况。
I have a date time as a string, eg. "2010-08-02", I'm trying to convert it to UTC with the following code snippet
DateTime.ParseExact("2010-08-02Z", "yyyy-MM-ddZ", CultureInfo.InvariantCulture)
When I print to the console, I get the following: 8/1/2010 5:00:00 PM.
Is there a reason why the date shows up as the date before the date I'm trying to parse? I could just add a day to this to advance to the original day, but I wanted to see if there's anything I'm doing wrong in the formatting that's causing this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
编辑:我有正确和不正确的混合体:)
它向您显示由 UTC 字符串表示的本地时间。在我看来,DateTime 并没有把这种事情说清楚,这很烦人。此外,我认为您不想使用“Z”作为时区的格式说明符;这实际上不是一个有效的格式说明符;它应该是“z”,-但这意味着“+01:00”之类的东西。我认为你应该使用“K”。坦率地说,这还不清楚,但如果你使用“K”,它肯定会正确往返(“Z”也会往返,但只是因为它忽略它,将其视为纯文本)。
您可以通过调用 ToUniversalTime 或(IMO 首选)指定 DateTimeStyles.AdjustToUniversal 作为额外参数来修复此问题:
EDIT: I had a mixture of being correct and not :)
It's showing you the local time represented by the UTC string. It's annoying that DateTime doesn't make this sort of thing clear, IMO. Additionally, I don't think you want to use 'Z' as the format specifier for the time zone; that's not actually a valid format specifier; it should be 'z', - but that's meant for things like "+01:00". I think you should be using 'K'. Frankly it's not clear, but if you use 'K' it round-trips correctly, certainly ('Z' roundtrips too, but only because it ignores it, treating it as plain text).
You can fix it by just calling
ToUniversalTime
, or (preferred IMO) specifyingDateTimeStyles.AdjustToUniversal
as an extra argument:2010-08-02 的 UTC 午夜恰好是 2010-08-01 的下午 5 点。
The UTC of midnight for 2010-08-02 happens to be at 5pm on 2010-08-01.
如果原始字符串只是格式为“2010-08-02”(不带 Z)的日期,那么为什么不呢:
ParseExact 可能会返回一个 Kind = Unspecified 的 DateTime,并且您可以根据需要将其设置为 UTC 或 Local希望使用SpecifyKind。
If the original string is just a date in the format "2010-08-02" (without the Z), then why not just:
ParseExact will presumably return a DateTime with Kind = Unspecified, and you can make it UTC or Local as you wish using SpecifyKind.