gpt4 book ai didi

ruby-on-rails - rails : distance_of_time_NOT_in_words

转载 作者:行者123 更新时间:2023-12-03 15:35:23 26 4
gpt4 key购买 nike

distance_of_time(Time.now, Time.tomorrow).days = 1 或类似的东西?如果没有,什么是实现这一目标的好方法?我知道有“from_now”,但为什么没有 from_whenever?

最佳答案

我不知道内置的通用解决方案,但如果您只需要比较几天,您可以这样做

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

使用 Times 你可以在几秒钟内做同样的事情。根据这些秒数,您可以构建一个合理的周、日、小时和分钟差异模型:

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

(或类似的东西,我还没有真正测试过代码,但你明白了 - 我希望如此)。

关于ruby-on-rails - rails : distance_of_time_NOT_in_words,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2430249/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com