1

According to this DateTime.Now vs. DateTime.UtcNow you store date time information in UTC and show it to user as DateTime.Now. If it is on web application, how does DateTime.Now know about user's location and adjusts UTC time accordingly? Is location inferred from header information that user passes in?

Community
  • 1
  • 1
dev.e.loper
  • 35,446
  • 76
  • 161
  • 247

3 Answers3

6

DateTime.Now does not know the user's location and adjust for it. It is based off the server the site is running on.

Doozer Blake
  • 7,677
  • 2
  • 29
  • 40
4

As Blake said, it doesn't.

If a server is calculating the current time for the end user, it must be based on information that user has provided. Otherwise, you typically would use javascript to provide the current date/time reference based on the local machine's clock.

The Evil Greebo
  • 7,013
  • 3
  • 28
  • 55
  • So every time I want to display a date I have to rinse it through a JavaScript function? Is there a cleaner way to do it? What about DateTime.ToLocalTime method? Although you still need to figure out where user is located and set DateTime.Kind property, you can do this on server side without using any client side code. – dev.e.loper Sep 26 '11 at 19:37
  • Javascript allows you to display the date/time based on the client's location. DateTime.ToLocalTime refers to the local time of the physical machine executing the code - so if your server is in New York, and it's midnight UMT, ToLocalTime will convert the time to 8pm (or 7pm...) the previous day, but your client, in California, *should* be seeing 5pm, not 8pm. You cannot tell on the server side where the client is coming in from automatically - you would have to collect that information client side (javascript again) and pass it back in a callback or some such. – The Evil Greebo Sep 26 '11 at 19:42
  • Looks like there are just two options. Use JavaScript like you suggest or if you store user's location you can calculate offset. http://www.4guysfromrolla.com/articles/040710-1.aspx – dev.e.loper Sep 26 '11 at 20:05
  • And the obvious problems with storing the user's location are, you have to know (or figure it out from the IP) where it is, allocate space to retain it, etc. – The Evil Greebo Sep 26 '11 at 20:07
  • Or you can ask user for their location and store it. Some apps do that. Of course this approach is also not foolproof. Besides making user enter their location, it would only work if that user stays in that time zone. If user moves to different time zone, they'll have to update their location. Meh. :-/ – dev.e.loper Sep 26 '11 at 20:44
  • Yes, asking the user and storing it would fall under the "have to know" category. – The Evil Greebo Sep 26 '11 at 20:55
1

DateTime.Now returns the current time according to the server, not the client.

James Johnson
  • 45,496
  • 8
  • 73
  • 110