问题
I have seen some answers about how to correct this. I have an object of type DateTime. I have assigned this object as shown below.
obj.TimeStamp = DateTime.UtcNow;
I cannot seem to find the right combination or code manipulation to get the correct date and time. It is always exactly 4 hours ahead of what the current time is.
This software will be deployed in various timezones.
Is there any reliable way to ensure the timestamp will be accurate across all time zones. My server time settings are correct.
Thank you.
回答1:
I know this question is old, but...
var localDate = DateTime.UtcNow.ToLocalTime()
https://msdn.microsoft.com/en-us/library/system.datetime.tolocaltime(v=vs.110).aspx
Read the notes in the MSDN article. This isnt't foolproof. But, if you are looking for a way to get the server time, this is a quick and easy way to get about as close as you can w/o getting too crazy.
回答2:
Interesting question! Dates and times are a notoriously hard problem to solve. It seems so simple, yet it's so difficult to actually do. We're all so used to looking at our watches for the time, when in fact it's a lot harder than that once you get time zones and daylight saving involved.
Take a look at the excellent Noda Time library. Even if you don't use it, the user guide provides some great insights into why dates and times are so hard a problem to solve.
I suspect your particular problem is related to the fact that your time zone is Eastern Time which is currently observing daylight saving, making your time zone 4 hours behind UTC.
In order to present the time to your users you'll need to know what time zone they are in. If they're in New York then you'll need to use UTC-04:00, if they're in California you'll need to use UTC-08:00 and if they're in New Delhi you'll need to use UTC+05:30.
However, this could change if/when they stop observing daylight saving, but be careful here as there is no hard-and-fast rule for this. Eastern Time stops observing daylight saving on the first Sunday in November, British Time stops on the last Sunday in October, Indian Time has no daylight saving at all and Southern Hemisphere regions observe daylight saving in the winter months (at least from the perspective of Northern Hemisphere regions).
Good luck!
来源:https://stackoverflow.com/questions/38722599/datetime-utcnow-is-4-hours-ahead