开发者

Rails: distance_of_time_NOT_in_words

As in, distance_of_time(Time.now, Time.tomor开发者_如何学运维row).days = 1 or something along those lines? If not, what would be a good way to achieve this? I know there is "from_now" but why wouldn't there be a from_whenever?


I don't know of a built-in general solution but if it's only days you need to compare, you can do

d = DateTime.now
d2 = DateTime.now.advance(:days => 1)
days_diff = (d2-d).to_i  # i.e., 1

Using Times you can do the same thing for seconds. From those seconds you can build a reasonable models of weeks, days, hours and minutes difference:

diff = (Time.now - Time.now.advance(:days => 38, :hours=>2, :minutes => 23)).abs
day_diff = diff % 1.week.seconds
weeks = (diff - day_diff) / 1.week.seconds
hour_diff = day_diff % 1.day.seconds
days = (day_diff - hour_diff) / 1.day.seconds
minute_diff = hour_diff % 1.hour.seconds
hours = (hour_diff - minute_diff) / 1.hour.seconds
second_diff = minute_diff % 1.minute.second
minutes = (minute_diff - second_diff) / 1.minute.seconds
fractions = second_diff % 1
seconds = (second_diff - fractions)

s=Struct.new(:weeks, :days, :hours, :minutes, :seconds)
s.new(weeks, days, hours, minutes, seconds)
s.weeks # 5
s.days # 2
s.minutes # 23
s.seconds # 0

(or something like this, I haven't really tested the code but you get the idea - I hope).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜