Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I calculate the next occurrence of a time 04:00 am EST?

What is an efficient way to get the next occurrence of 04:00 am EST?

For example, if the date and time is 2013/11/19 01:30:00 then next occurrence would be 2013/11/19 04:00:00, however if it is 2013/11/19 17:00:00 then next occurrence would be 2013/11/20 04:00:00

like image 538
Sampat Badhe Avatar asked Nov 19 '13 09:11

Sampat Badhe


3 Answers

Try following

time = if Time.now.hour >= 4 
          Time.now+1.day 
       else
          Time.now
       end

time.strftime("%Y-%m-%d 04:00:00").to_datetime

OR Just

(Time.now+(Time.now.hour >= 4 ? 1 : 0).day).strftime("%Y-%m-%d 04:00:00").to_datetime
like image 57
RORprasad Avatar answered Oct 30 '22 08:10

RORprasad


You can get the hour you are looking for using:

time = DateTime.now
time.change({hour: 4, min: 0, sec: 0})

this will give you a time variable at 04:00 am. You can then do time+1 or time-1 to move forward or backward one day at a time.

Eg. (saving one loc)

time = DateTime.now.change({hour: 4, min: 0, sec: 0})
time += 1 if time < DateTime.now
like image 37
marzapower Avatar answered Oct 30 '22 06:10

marzapower


Try following

time = Time.now.hour >= 4 ? Time.now+1.day : Time.now
time.strftime("%Y-%m-%d 04:00:00").to_datetime
like image 31
Salil Avatar answered Oct 30 '22 06:10

Salil