How to calculate the next occurrence of time 04:00 am EST?

What is an effective way to get the next appearance at 04:00 AM EST?

For example, if the date and time is 2013/11/19 01:30:00, then in the following case it will be 2013/11/19 04:00:00, however if it is 2013/11/19 17:00: 00, then next appearance will be 2013/11/20 04:00:00

+7
ruby datetime ruby-on-rails ruby-on-rails-3
source share
5 answers

Try to execute

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 simply

 (Time.now+(Time.now.hour >= 4 ? 1 : 0).day).strftime("%Y-%m-%d 04:00:00").to_datetime 
+7
source share

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 the time variable at 04:00. 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 
+2
source share

Try to execute

 time = Time.now.hour >= 4 ? Time.now+1.day : Time.now time.strftime("%Y-%m-%d 04:00:00").to_datetime 
+2
source share

A bit hacked:

 if (DateTime.now.to_i - Date.today.to_datetime.to_i) > (60 * 60 * 4) next_4am = (Date.today + 1.day).to_datetime + 4.hours else next_4am = Date.today.to_datetime + 4.hours end 
+1
source share

I would do it like this:

 date, time = Time.now, [4,0,0] date += 24*60*60 if date.hour >= 4 p Time.new(*date.to_a[3..5].reverse, *time) #=> 2013-11-20 04:00:00 +0100 # date.to_a[3..5].reverse gets the date our from the Time object 
0
source share

All Articles