I have tried such code, but it doesn't work:
require 'time_diff'
cur_time = Time.now.strftime('%Y-%m-%d %H:%M')
time_diff_components = Time.diff(@art.datetime_of_update, Time.parse(cur_time))
if @art.PRICEM.to_f >= eprice.to_f || @art.PRICEM.blank? && time_diff_components[:hour] < 3 &&
but timediff is 0, in db time looks like this:
2012-08-28 19:53:12
How calculate difference in hour's between now and db?
Firstly, you should look at these two lines:
cur_time = Time.now.strftime('%Y-%m-%d %H:%M')
time_diff_components = Time.diff(@art.datetime_of_update, Time.parse(cur_time))
Why would you format the time and then only use the value as the input to a parsing operation? Surely it would be simpler - and less fragile - to write:
time_diff_components = Time.diff(@art.datetime_of_update, Time.now)
I don't know why Time.diff
isn't working for you (I'm not a Ruby dev), but if the aim is to check whether the article was updated "less than 3 hours ago" then there's a simpler approach: subtract three hours from the current time, and compare the article's update time with that limit:
limit_time = Time.now + 3.hours
if @art.PRICEM.to_f >= eprice.to_f || @art.PRICEM.blank? && @art.datetime_of_update >= limit_time
If you don't have to be precise, you can use Rails' time_ago_in_words
helper.
time_ago_in_words(Time.now - 3.hours)
#=> about 3 hours
of course, depending on the time difference, this can return 'minutes', 'days', etc. as well.
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.