开发者

Date time for time zones

开发者 https://www.devze.com 2023-03-30 21:28 出处:网络
In C# DateTime.Now.Day Vs. DateTime.Now.Date.Day => What is the actual difference? For say, when i am PST zone say 8 PM - 08/26, when I call

In C#

DateTime.Now.Day Vs. DateTime.Now.Date.Day => What is the actual difference?

For say, when i am PST zone say 8 PM - 08/26, when I call

DateTime.Now.Day //26
Da开发者_运维问答teTime.Now.Date.Day //26

For say, when i am EST zone say 8 PM - 08/26, when i call

DateTime.Now.Day //27
DateTime.Now.Date.Day //27

I am trying to get Day from datetime or a date, so that I want to use a day which can be consistent in any PST/EST/CST time zones, any thoughts?


There is absolutely no difference (see the DateTime Structure documentation). The .Date identifier simply strips out the time information from the DateTime object you're working with.

If you want consistent time, use UTC time, and the DateTime.UtcNow property.


Short answer: use DateTime.UtcNow.

Long answer:

Break it down in terms of expressions and the type system:

DateTime is a value type with a few static members. One of those members is Now. The static Now property returns an instance of a DateTime struct populated with the value of the current time. But it's still a DateTime type instance.

The Date member is available to instances of the DateTime type, and returns a new DateTime instance with the values for the time component zero'd out. But it's still just a DateTime type instance.

The Day member is available to instances of the DateTime type, and returns an integer for the current day of the month.

You want to know, first of all, if there is a difference between DateTime.Now.Date.Day and DateTime.Now.Day. Logically, you would think there is none, but I do want to point out one thing on the Now property: it's not magic. Code runs, and therfore time passes, after you access the Now property and while executing the .Date.Day expression. During that time, the original Now value used becomes stale. This expression is very fast and hardly takes any time at all — but it's not zero. If you're not careful, you could be creating a race condition.

Secondly, you want to know about timezones and getting consistent dates. The trick here is whether you really care only about the US timezones listed and whether you'll have any times near midnight in any zone. But really the best option is to look at another member of the DateTime data type: it's .UtcNow property. This will return the same value regardless of what timezone you are in. You can use it to evaluate a time that will consistent across all your timezones.

0

精彩评论

暂无评论...
验证码 换一张
取 消