I am storing information i开发者_高级运维n a database and setting my POCO's property to DateTime.Now.
When this value is displayed it is appearing as the PST time. I would like it to to display as GMT time.
Do I do something like this to display/store it or is there a better way?
TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("GMT");
var GMTTime = TimeZoneInfo.ConvertTimeToUtc(DateTime.Now, tz));
Also it needs to consider Daylight Savings as UK changes its clocks at different times in the year than USA:
UPDATE: I have found that in the TimeZone setting you can pass either GMT Standard Time or Greenwich Mean Time, the first taking into account DST
Store it as UTC. It's designed for universal timezone-independent time.
DateTime currentUtcTime = DateTime.UtcNow;
DateTime localTime = currentUtcTime.ToLocalTime();
DateTime backToUtcAgain = localTime.ToUniversalTime();
Whether a given DateTime
is already UTC or local time is determined by DateTime.Kind
. You have to keep this in mind when serializing/deserializing DateTime
values (e.g from a database) because this information is often not stored and when you get your DateTime
back, it will most of the time have the value DateTimeKind.Unspecified
, which may cause issues with conversion methods. I just make sure to force DateTimeKind.Utc
when I load something in from a persistent data store.
there's DateTime.UtcNow
if that meets your needs.
Have a look at DateTimeOffset.
I'd propose to change your DateTime property to this type
MSDN DateTime vs. DateTimeOffSet
You could add it into an extension method to make it nicer
public static DateTime ConvertToGreenwichMeanTime(this DateTime utcDateTime)
{
return TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time"));
}
Then just call it
DateTime.UtcNow.ConvertToGreenwichMeanTime();
精彩评论