T开发者_运维问答o me they're both the same. Is UtcNow simply a shortcut?
Actually it's the other way around. The Now
property is implemented as:
public static DateTime Now {
get {
return UtcNow.ToLocalTime();
}
}
It isn't a shortcut, DateTime.Now uses DateTime.UtcNow internally and then applies localization. In short, use ToUniversalTime() if you already have DateTime.Now and need to convert it to UTC, use DateTime.UtcNow if you just want to retrieve the current time in UTC.
There is a long example in the Documentation for UtcNow which shows them to be the same.
Well, the actual implementation is (you can see it on referencesource):
public static DateTime Now {
get {
Contract.Ensures(Contract.Result<DateTime>().Kind == DateTimeKind.Local);
DateTime utc = UtcNow;
Boolean isAmbiguousLocalDst = false;
Int64 offset = TimeZoneInfo.GetDateTimeNowUtcOffsetFromUtc(utc, out isAmbiguousLocalDst).Ticks;
long tick = utc.Ticks + offset;
if (tick>DateTime.MaxTicks) {
return new DateTime(DateTime.MaxTicks, DateTimeKind.Local);
}
if (tick<DateTime.MinTicks) {
return new DateTime(DateTime.MinTicks, DateTimeKind.Local);
}
return new DateTime(tick, DateTimeKind.Local, isAmbiguousLocalDst);
}
}
ToUniversalTime()
calls TimeZoneInfo.ConvertTimeToUtc(this, TimeZoneInfoOptions.NoThrowOnInvalidTime)
while UtcNow is just:
long ticks = 0;
ticks = GetSystemTimeAsFileTime();
return new DateTime( ((UInt64)(ticks + FileTimeOffset)) | KindUtc);
I think that using DateTime.UTCNow would consider the DateTime.Kind property's value as UTC whereas with ToUniversalTime you can provide the Kind property with a local datetime object.
精彩评论