DateTime.Now vs. DateTime.UtcNow

后端 未结 13 1475
暗喜
暗喜 2020-11-28 17:43

I\'ve been wondering what exactly are the principles of how the two properties work. I know the second one is universal and basically doesn\'t deal with time zones, but can

13条回答
  •  無奈伤痛
    2020-11-28 18:35

    One main concept to understand in .NET is that now is now all over the earth no matter what time zone you are in. So if you load a variable with DateTime.Now or DateTime.UtcNow -- the assignment is identical.* Your DateTime object knows what timezone you are in and takes that into account regardless of the assignment.

    The usefulness of DateTime.UtcNow comes in handy when calculating dates across Daylight Savings Time boundaries. That is, in places that participate in daylight savings time, sometimes there are 25 hours from noon to noon the following day, and sometimes there are 23 hours between noon and noon the following day. If you want to correctly determine the number of hours from time A and time B, you need to first translate each to their UTC equivalents before calculating the TimeSpan.

    This is covered by a blog post i wrote that further explains TimeSpan, and includes a link to an even more extensive MS article on the topic.

    *Clarification: Either assignment will store the current time. If you were to load two variables one via DateTime.Now() and the other via DateTime.UtcNow() the TimeSpan difference between the two would be milliseconds, not hours assuming you are in a timezone hours away from GMT. As noted below, printing out their String values would display different strings.

提交回复
热议问题