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

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

问题描述



更具体地说:如果我在一个时区创建一个DateTime对象,然后切换到另一个时间区域并运行ToUniversalTime(),它如何知道转换是否正确完成,并且时间仍然准确地表示?



谢谢

解决方案

对于 DateTime 对象,没有隐含的时区。如果您运行 ToUniversalTime(),则会使用运行代码的上下文的时区。



例如,如果我从1/1/1970的纪元创建一个 DateTime ,它给我相同的 DateTime 对象,无论我在世界的哪个地方。



如果我运行 ToUniversalTime() m在格林威治运行代码,然后我得到同样的时间。如果我在温哥华住的时候做,那么我得到一个-8小时的偏移量 DateTime 对象。



这就是为什么当您需要进行任何类型的日期转换或本地化时,将数据库中的时间相关信息作为UTC时间很重要。考虑你的代码库是否被转移到另一个时区的服务器设施;)



编辑:Joel的答案中的注释 - DateTime 对象默认键入为 DateTimeKind.Local 。如果您解析日期并将其设置为 DateTimeKind.Utc ,则 ToUniversalTime()不执行转换。



这里有一篇关于Best的文章使用日期时间编码的实践以及有关将日期时间转换为 Net


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

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?

Thanks

解决方案

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.

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.

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.

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 ;)

Edit: 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.

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天全站免登陆