Reputation: 7300
To me they're both the same. Is UtcNow simply a shortcut?
Upvotes: 37
Views: 23522
Reputation: 5238
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.
Upvotes: 7
Reputation: 29431
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);
Upvotes: 2
Reputation: 1548
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.
Upvotes: 1
Reputation: 700292
Actually it's the other way around. The Now
property is implemented as:
public static DateTime Now {
get {
return UtcNow.ToLocalTime();
}
}
Upvotes: 35
Reputation: 136104
There is a long example in the Documentation for UtcNow which shows them to be the same.
Upvotes: 5