简体   繁体   中英

How does C# DateTime determine it's Now and Today times

Couldn't find anything on the internet nor the documentation on this. Where does C# get it's DateTime.Now or DateTime.Today from? These are localized values. Is it determined by Windows? Or does IIS influence this? I want to know what exactly parses the real now time to C# and what can influence it.


Why I want to know this

I am having some weird API behavior where some things are returned hours before they should. Which is most likely related to time zones. VPS and client are in the same time zone so I am wondering what can influence such behavior.

I am doing a hard ...FromDate.Date <= DateTime.Today.Date and for some reason I sometimes get records that are "from" tomorrow. Where 2021-02-21 <= 2021-02-20 seems to be "true". True meaning that the DateTime.Today seems to be off. Only seeing this behavior around after 10 PM so hours before actual midnight suggesting it has something to do with time zones.

If you have any idea on this behavior please tell me

Thanks to @Matthew Watson for helping me get here.

For anyone in the future

The DateTime.Now is received from the system. First it will get UtcNow and then applying a local offset (if there is any).

See source code line 1051

The DateTime.Today property just returns DateTime.Now.Date

See source code line 1262


UtcNow is received by the internal extern method GetSystemTimeWithLeapSecondsHandling . Which I couldn't find a implementation for.

See source code

From my experience, DateTime.Now or DateTime.Today checks your server's time. If you are running your application from the server, most likely it is checking your server time

So technically, according to Microsoft documentation, the DateTime.Now property returns the DateTime object that is stored on the machine to the current date and time, interpreted as local time. On the other side, DateTime.Today, is an object set to today's date, with the time component set to 00:00:00. The Today property is appropriate for use in programs that only deal with dates as it returns the current date without the present time. I believe what influences this is the time set on your local machine, I doubt that IIS influences this. However, those values can be influenced if you're running your application on a server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM