Reputation: 340171
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. TimeSpan
s 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?
Upvotes: 6
Views: 6302
Reputation: 1499790
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.
Upvotes: 11
Reputation: 3569
A little hint - .NET supports arithmetic operations on DateTime objects, and returns a TimeSpan object. Thus, you can do the following:
DateTime fromDate = ....
DateTime toDate = ....
TimeSpan diff = toDate - fromDate;
and you can expand this to:
DateTime fromDate = DateTime.Now;
DateTime toDate = DateTime.Now.addMinutes(x);
if ((toDate - fromDate).TotalMinutes > 15) {
...
}
Upvotes: 2
Reputation: 29401
So you're only interested in the time component of the date.
if(DateTime.Now.TimeOfDay > startHour.TimeOfDay)
{
// do stuff
}
What's wrong with doing this?
Upvotes: 0
Reputation: 6453
You should use TimeSpan for startHour and endHour. When comparing with now, you should "convert" them to a full DateTime or get the Time with DateTime.TimeOfDay as mentioned by Jon Skeet.
TimeSpan startHour = new TimeSpan(12, 25, 43);
DateTime now = DateTime.Now;
if (now.CompareTo(DateTime.Today.Add(startHour)) > 0) {
//...
}
or
TimeSpan startHour = new TimeSpan(12, 25, 43);
DateTime now = DateTime.Now;
if (now.TimeOfDay.CompareTo(startHour) > 0) {
//...
}
Upvotes: 1