I'm sure this is very easy, but I've got a sudden mental block.
I'm trying to get a DateTime object for the next occurence of 3am. For example, if DateTime.Now
is 16/july/2009 : 12:04pm
- the next occurance of 3am would be 17/july/2009 : 03:00
However, if DateTime.Now
was 17/july/2009 : 01:00
then the next occurence would still be 17/july/2009 : 03:00
(not the day after).
Does that make sense?
One option:
DateTime now = DateTime.Now;
DateTime today3am = now.Date.AddHours(3);
DateTime next3am = now <= today3am ? today3am : today3am.AddDays(1);
Another:
DateTime now = DateTime.Now;
DateTime today = now.Date;
DateTime next3am = today.AddHours(3).AddDays(now.Hour >= 3 ? 1 : 0)
Lots of ways of skinning that particular cat :)
This is all in local time of course, which means you don't need to worry about time zones. Life becomes trickier if you want to get time zones involved...
Note that it's a good idea to take DateTime.Now
once to avoid problems if the date rolls over while you're calculating...
DateTime now = DateTime.Now;
DateTime threeAM = now.Date.AddHours(3);
if (threeAM < now)
threeAM = threeAM.AddDays(1);
//just add 24 - 3 = 21 hours and get Today (start of day) and Add 3 hour
DateTime now = DateTime.Now.AddHours(21).Today.AddHours(3);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With