简体   繁体   中英

Daylight saving issue while calculating Elapsed Time in C#

I'm trying to calculate elapsed time for my project.
For example,
Start time is 06-Nov-2011 01:59:58 AM
End Time is 06-Nov-2011 01:00:00 AM
Actual Elapsed Time is 00:00:02
But getting Elapsed Time is -00:59:58 (Due to Daylight Saving, clock went back 1 hour)
How can i calculate this in better way with correct elapsed time during Daylight Saving?

Code:

DateTime startDttm = DateTime.Parse("Nov 06, 2011 01:59:58 AM");  
DateTime endDttm = DateTime.Parse("Nov 06, 2011 01:00:00 AM");  
TimeSpan elapsedTime = endDttm.Subtract(startDttm);  
Console.WriteLine("Elapsed Time - " + elapsedTime);

Your values are basically ambiguous - both of those times occurred twice assuming the clocks went back at 2am.

If you know that you want to treat the start time as the earlier option, and the end time as the later option, you can use Noda Time :

using System;
using NodaTime;
using NodaTime.Text;

public class Test
{
    static void Main(string[] args)
    {
        var pattern = LocalDateTimePattern.CreateWithInvariantInfo
              ("MMM dd, yyyy HH:mm:ss tt");
        LocalDateTime start = pattern.Parse("Nov 06, 2011 01:59:58 AM").Value;
        LocalDateTime end = pattern.Parse("Nov 06, 2011 01:00:00 AM").Value;

        DateTimeZone zone = DateTimeZone.ForId("America/Chicago");

        // Where this is ambiguous, pick the earlier option
        ZonedDateTime zonedStart = zone.AtEarlier(start);

        // Where this is ambiguous, pick the later option
        ZonedDateTime zonedEnd = zone.AtLater(end);

        Duration duration = zonedEnd.ToInstant() - zonedStart.ToInstant();

        // Prints 00:00:02
        Console.WriteLine(duration.ToTimeSpan());
    }        
}

In an ideal world, however, you wouldn't be having to parse ambiguous local times and guess whether they're meant to be earlier or later. What's the context here?

If at all possible, change your data source to record UTC date/times instead of local dates/times... ideally in a more parse-friendly format, eg yyyy-MM-ddTHH:mm:ss

Use Coordinated Universal Time to store your timestamps. Whenever you compare two timestamps in Coordinated Universal Time, you get the correct difference.

In C# you get the current timestamp in that format by using DateTime dt = DateTime.UtcNow .

See also http://en.wikipedia.org/wiki/Coordinated_Universal_Time .

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