简体   繁体   中英

Strange behavior from DateTime objects

I do the following:

var now = DateTime.Now;
var utc = DateTime.UtcNow;
var timeSpan = now - utc;

Console.WriteLine("Now is: " + now.ToString("yyyy-MM-dd HH:mm:ss:ms") + " utc is: " + utc.ToString("yyyy-MM-dd HH:mm:ss:ms") + " timeSpan: " +
                    timeSpan.TotalMinutes);

Console.ReadKey();

It gives the following result: 安慰 And if I take the timespan.hours (which is the one I actually use) it revelas 1? Should be 2 What am I doing wrong there?

There is some time passes between you get times (system can even switch processes between these two calls):

 var now = DateTime.Now;
 // some time passes here
 var utc = DateTime.UtcNow;

Thats why you have less than 2 hours between two values. You should get time only once and then convert it to local time:

 var utc = DateTime.UtcNow;
 var now = utc.ToLocalTime();
 // timeSpan: 120

Or use TimeZoneInfo.ToUniversalTime to convert local time to UTC time:

 var now = DateTime.Now;
 var utc = TimeZone.CurrentTimeZone.ToUniversalTime(now);

The reason is simple: your calculation introduces an error by taking the time twice. The final result is slightly wrong, but the time taken to make the calls.

The solution is simpler.

  Console.WriteLine(TimeZoneInfo.Local.BaseUtcOffset.Hours);
  Console.WriteLine(TimeZoneInfo.Local.GetUtcOffset(DateTime.Now).Hours);

There is no need to get or convert times when what you actually want is time zone info. The first line gets the "normal" local time offset; the second gets the offset for 'now' in case your timezone is subject to daylight saving or other adjustments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM