Reputation: 21
I'm trying to calculate elapsed time for my project.
For example,
Start time is 06-Nov-2011 01:59:58 A.M
End Time is 06-Nov-2011 01:00:00 A.M
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);
Upvotes: 2
Views: 1554
Reputation: 1500815
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, e.g. yyyy-MM-ddTHH:mm:ss
Upvotes: 6
Reputation: 33139
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.
Upvotes: 0