将其转换为日期时间格式C# [英] Converting this into a date time format C#

查看:52
本文介绍了将其转换为日期时间格式C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我正在尝试读取Twitter feed XML的日期/时间,当前格式为:Fri May 03 15:22:09 +0000 2013但是我的C#没有将其作为Date/读取时间类型.

Okay, so i am trying to read the date/time of the Twitter feed XML, it is currently in this format: Fri May 03 15:22:09 +0000 2013 However my C# is not reading it as a Date/Time type.

这就是我得到的:

  ArticleDate = DateTime.Parse(d.Element("created_at").Value)

created_at包含:2013年5月3日星期五15:22:09 +0000 2013格式

created_at contains the: Fri May 03 15:22:09 +0000 2013 Format

推荐答案

请小心.您还给您的时间以UTC为单位.您可能最终会无意间让您的本地时区影响结果.

Be careful. The times you are given back are in UTC. You may end up unintentionally letting your local time zone influence the result.

例如,其他答案之一建议此代码:

For example, one of the other answers suggested this code:

DateTime dt = DateTime.ParseExact("Fri May 03 15:22:09 +0000 2013",
                                  "ddd MMM dd HH:mm:ss zzz yyyy",
                                  CultureInfo.InvariantCulture);

在我位于亚利桑那州(UTC-7)的计算机上,此操作的结果是:

The result of this on my computer, which is in Arizona (UTC-7), is:

5/3/2013 8:22:09 AM   (dt.Kind == DateTimeKinds.Local)

虽然这是我当地时间的正确时刻,但不是我所得到的,除非您密切注意 .Kind 属性,否则可能不是您所期望的.

While this is the correct moment in my local time, it is not what was given to me, and it probably not what you are expecting unless paying close attention to the .Kind property.

您可以改为执行以下操作:

You can instead do the following:

DateTime dt = DateTime.ParseExact("Fri May 03 15:22:09 +0000 2013",
                                  "ddd MMM dd HH:mm:ss zzz yyyy",
                                  CultureInfo.InvariantCulture,
                                  DateTimeStyles.AdjustToUniversal);

这将返回:

5/3/2013 3:22:09 PM   (dt.Kind == DateTimeKinds.Utc)

哪个更适合您的开始.

现在,这假设从Twitter返回的值将始终为UTC.似乎是这种情况,根据其常见问题解答.但有人可能会争辩说,既然给了我们一个偏移量,那么按规定使用该偏移量可能更正确.如果偏移量曾经改变过,我们不希望我们的代码中断.因此,更适合使用 DateTimeOffset 类.

Now, this assumes that the values coming back from Twitter will always be UTC. That seems to be the case, according to their FAQ. But one could argue that since we are given an offset, it might be more correct to use that offset as provided. If the offset ever changes, we don't want our code to break. Therefore, it is more appropriate to use the DateTimeOffset class.

DateTimeOffset dto = DateTimeOffset.ParseExact("Fri May 03 15:22:09 +0000 2013",
                                               "ddd MMM dd HH:mm:ss zzz yyyy",
                                               CultureInfo.InvariantCulture);

其结果是:

5/3/2013 3:22:09 PM +00:00

这篇关于将其转换为日期时间格式C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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