DateTime.ToUniversalTime和TimeZoneInfo.ConvertTimeToUtc之间的区别是什么区别、ToUniversalTime、DateTime、ConvertTim

2023-09-03 06:42:33 作者:别把最疼爱你的人弄丢了

我刚开始正确地约推出了web应用程序,这将需要做的事情,用户在他们的一天开始思考,说早上6点。此外,在它们的天结束。

I'm just starting to think properly about rolling out a webapp that will need to do things to users at the start of their day, say 6am. Also at the end of their days.

无论我一直在阅读有关的人说了很多只用.ToUniversalTime存储在UTC时间,但是当我尝试这样做(我怀疑)没有工作,它只是走动的时候一个小时(我在英国,所以我认为这是做了一些从格林尼治标准​​时间为UTC偏移,虽然这并没有什么意义,我,作为节能日光应该在此刻被关闭)。

Everywhere I've been reading about people saying a lot just to use .ToUniversalTime to store the time in UTC, but when I tried this (as I suspected) it didn't work, and it just moved the time about by an hour (I'm in the UK, so I thought this was to do with some offset from GMT to UTC, although that doesn't make sense to me, as day light saving should be off at the moment).

我在存储的用户时区数据库字段,所以当我开始使用ConvertTimeToUtc和fromUtc,它开始做我期待它做的事。虽然再次声明,我不知道如果我必须建立在一些逻辑自己做夏令时转换,还是应该为我做的。

I have a field in the db that stores the users timezone, and so when I started using ConvertTimeToUtc and fromUtc , it started doing what I was expecting it to do. Although again I'm not sure if I have to build in some logic myself to do daylight saving conversions, or it should do it for me.

我主要是想知道为什么每个人都在谈论.ToUniversalTime,因为它确实似乎没有帮我,我不明白他们怎么可能知道多少抵消了时间就转移到UTC,而第二种方式是有道理的。

I am mainly wondering why everyone was talking about .ToUniversalTime, as it really didn't seem to help me, and I couldn't understand how it could possibly know how much to offset the time to shift it to UTC, whereas the second way made sense.

有人能解释每一个方法怎么可能是有用的?

Could someone explain how each methods could be useful?

推荐答案

如果您在计算机上运行的code在不同的时区,在您的计算仍然去上班?这就是人们存储和处理所有DateTime是否为UTC - 它消除任何含糊之处。你不会需要存储用户的时区。任何机器,在任何地方,可以从数据库中提取的日期,并将其转换到和来自本地时间轻松。

If you run the code on a machine in a different timezone, are your calculations still going to work? This is the reason people store and treat all DateTimes as UTC - it removes any ambiguity. You wouldn't need to store the user's timezone. Any machine, anywhere, can pull a date from the database and convert it to and from local times with ease.

如果你存储的时间在其他时区,那么你必须把它拉出来,计算偏移到所需的时区,包括保理在夏令时间和国际日期变更线的考虑。在你的情况,你也存储额外的不必要的信息。

If you're storing times in some other timezone, then you have to pull it out, calculate the offset to the desired timezone, including factoring in daylight savings times and international dateline considerations. In your case, you're also storing extra unnecessary information.