开发者

how to calculate time difference in rails

I have a field that is a timestamp. I want to calculate the time difference between that timestamp and the current time and show the time as something humanly readable like

2 days remaining #don't show hours whe开发者_如何学编程n > 1 day is remaining

once less than 1 day is remaining I'll have a javascript countdown ticker.


I've built the dotiw library to do exactly this: http://github.com/radar/dotiw.

This is based off the distance_of_time_in_words method in Rails which is not quite accurate enough, and so I've made it more accurate with dotiw.


Try this:

if end_date < Time.now # ended already
  return 'Ended'
elsif end_date > (Time.now + 1.day) # more than 1 day away
  diff_in_days = ((end_date - Time.now).to_i / 1.day)
  days_string = diff_in_days.to_s
  days_string += (diff_in_days > 1) ? ' Days' : ' Day'
  return days_string
else # ending today
  diff_in_HMS = Time.at(end_date - Time.now).gmtime.strftime('%R:%S')
  return diff_in_HMS
end

It prints "X Days" if end_date is > 1 day away, HH:MM:SS if ending today, and "Ended" if end_date was in the past.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜