简体   繁体   中英

how to add time with Time.now in rails

In controller:

@delivery_time=(Time.now + @hotel.deliverytime.to_i).strftime("%I:%M")

where deliverytime=00:30:00

I am getting a wrong answer of @delivery_time .I am getting 2014-12-12 05:50:00 after adding Time.now=2014-12-12 17:20:00 and deliverytime=00:30:00 .The answer should be 2014-12-12 17:50:00 . What am I doing wrong?

Try like that:--

duration = @hotel.deliverytime.hour * 60 * 60 + @hotel.deliverytime.min * 60 + @hotel.deliverytime.sec
@delivery_time=(Time.now + duration).strftime("%I:%M")

Rails allows you to add a specific amount of days, hours, minutes,etc

Time.now+30.minutes

You can also do

Time.now+1.hour
Time.now+1.day

If your time is in a 00:00:00 string you can do something like

@delivery_time=(Time.now + (@hotel.deliverytime.split(':')[0].to_i*3600 + @hotel.deliverytime.split(':')[1].to_i*60 + @hotel.deliverytime.split(':')[2].to_i).seconds ).strftime("%I:%M")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM