Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Handle Actual Time with Durations in C#?

What's the preferred approach to compare a complete DateTime instance with an hour, minute, and second which represents an actual time of day, with the ability to operate over those triplets (eg add hours, minutes seconds..)?


My current approach is something like

DateTime startHour = new DateTime(1900,1,1,12,25,43);
DateTime endHour = new DateTime(1900,1,1,13,45,32);

// I need to, say, know if a complete DateTime instance 
// is later than startHour plus 15 minutes

DateTime now = DateTime.Now();

startHour = startHour.addMinutes(15);

if (now.CompareTo(new DateTime(now.Year, now.Month, now.Day, startHour.Hour, 
                    startHour.Minute, startHour.Second)) > 0) 
{
    //I can do something now
}

This is very cumbersome and even failure prone. TimeSpans are not a solution as far as I can see, because they represent spans and aren't bound by the 24 hours limit (a TimeSpan of 56 hours 34 minutes is valid.)

What's the preferred approach for this type of calculations?

like image 546
Vinko Vrsalovic Avatar asked Sep 10 '09 23:09

Vinko Vrsalovic


People also ask

How to deal with time in C#?

To work with date and time in C#, create an object of the DateTime struct using the new keyword. The following creates a DateTime object with the default value. The default and the lowest value of a DateTime object is January 1, 0001 00:00:00 (midnight). The maximum value can be December 31, 9999 11:59:59 P.M.

How do I get the time difference between two times in C#?

DateTime date1 = new DateTime(2018, 7, 15, 08, 15, 20); DateTime date2 = new DateTime(2018, 8, 17, 11, 14, 25); Now, get the difference between two dates. TimeSpan ts = date2 - date1; Get the result i.e. the difference in hours.

What is the difference between DateTime and TimeSpan in C#?

The TimeSpan struct represents a duration of time, whereas DateTime represents a single point in time. Instances of TimeSpan can be expressed in seconds, minutes, hours, or days, and can be either negative or positive.

What is TimeSpan C#?

C# TimeSpan struct represents a time interval that is difference between two times measured in number of days, hours, minutes, and seconds. C# TimeSpan is used to compare two C# DateTime objects to find the difference between two dates.


1 Answers

It's not at all clear what you mean by "is greater than startHour"... but taking

TimeSpan startHour = new TimeSpan(12, 25, 43);
if (endHour.TimeOfDay > startHour)
{
    ...
}

... works pretty simply.

By all means add argument checking to make sure that you don't specify a value for startHour which is < 0 or > 23 hours, but that's all pretty easy.

.NET's date and time API is quite primitive (even in 3.5) compared with, say, Joda Time - but in this particular case I think it's not too bad.

like image 193
Jon Skeet Avatar answered Nov 06 '22 13:11

Jon Skeet