Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime of next 3am occurrence

Tags:

c#

datetime

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?

like image 987
Alex Avatar asked Jul 17 '09 11:07

Alex


3 Answers

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...

like image 157
Jon Skeet Avatar answered Nov 20 '22 08:11

Jon Skeet


DateTime now = DateTime.Now;
DateTime threeAM = now.Date.AddHours(3);

if (threeAM < now)
    threeAM = threeAM.AddDays(1);
like image 5
LukeH Avatar answered Nov 20 '22 09:11

LukeH


//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);
like image 3
Chernikov Avatar answered Nov 20 '22 08:11

Chernikov