如何DateTime.ToUniversalTime()的工作? [英] How does DateTime.ToUniversalTime() work?

查看:466
本文介绍了如何DateTime.ToUniversalTime()的工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何皈依为UTC从标准DateTime格式的工作?

How does the convertion to UTC from the standard DateTime format work?

更具体地讲:如果我在一个时区创建DateTime对象,然后切换到另一个时区,并在其上​​运行ToUniversalTime(),它是如何知道转换正确完成,而且时间还精确地重新presented?

More specifically: if I create a DateTime object in one time zone and then switch to another time zone and run ToUniversalTime() on it, how does it know the conversion was done correctly and that the time is still accurately represented?

感谢

推荐答案

有连接到的DateTime 对象没有隐时区。如果您运行 ToUniversalTime()就可以了,它使用了code在运行的环境的时区。

There is no implicit timezone attached to a DateTime object. If you run ToUniversalTime() on it, it uses the timezone of the context that the code is running in.

例如,如果我创建一个的DateTime 从1/1/1970时代,它给了我同样的的DateTime 对象无论在世界何处,我。

For example, if I create a DateTime from the epoch of 1/1/1970, it gives me the same DateTime object no matter where in the world I am.

如果我跑就可以了ToUniversalTime()当我运行code在格林威治,然后我得到了同样的时间。如果我这样做,虽然我住在温哥华,然后我得到的-8小时的偏移的DateTime 对象。

If I run ToUniversalTime() on it when I'm running the code in Greenwich, then I get the same time. If I do it while I live in Vancouver, then I get an offset DateTime object of -8 hours.

这就是为什么存储时间相关的信息在数据库中的UTC时间是很重要的,当你需要做任何形式的日期转换或本地化。试想,如果你的codeBase类移动了到服务器设备在另一个时区)

This is why it's important to store time related information in your database as UTC times when you need to do any kind of date conversion or localization. Consider if your codebase got moved to a server facility in another timezone ;)

编辑:注意从乔尔的回答 - 的DateTime 默认对象类型为 DateTimeKind.Local 。如果你分析一个日期,并将其设置为 DateTimeKind.Utc ,然后 ToUniversalTime()不进行转换。

note from Joel's answer - DateTime objects by default are typed as DateTimeKind.Local. If you parse a date and set it as DateTimeKind.Utc, then ToUniversalTime() performs no conversion.

和这里的一对文章最佳实践与日期时报编码,与文章在与.net 的转换DateTime是否。

And here's an article on "Best Practices Coding with Date Times", and an article on Converting DateTimes with .Net.

这篇关于如何DateTime.ToUniversalTime()的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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