如何评估年、月和日的日期差异(ruby)?

时间:2021-06-25 21:32:22

I have to make a simple difference between two dates:

我必须在两个日期之间做一个简单的区别:

Date.parse("2009-06-20") - Date.today

This gives me the difference of the dates in days.

这让我知道了日期的不同。

Anyone know a way to easily convert that to the following format:

任何人都知道一种简单地将其转换为以下格式的方法:

The event occurred X years, Y months and Z days ago

Thank you.

谢谢你!

5 个解决方案

#1


6  

Found the answer here:

在这里找到了答案:

More precise distance_of_time_in_words

更精确的distance_of_time_in_words

with this gem:

这个宝石:

https://github.com/radar/dotiw

https://github.com/radar/dotiw

#2


5  

You may be looking for distance_of_times_in_words

您可能正在寻找distance_of_times_in_words

#3


3  

There is a RubyGem which returns Time difference in a hash like {:year => 0, :month => 0,...}

有一个RubyGem,它在一个散列中返回时差,比如{:year =>,:month => 0,…}

The link is : https://rubygems.org/gems/time_diff

链接是:https://rubygems.org/gems/time_diff。

#4


1  

This is an example for difference in days, hours, seconds. Add the fields that you need.

这是天数、小时、秒的差异的一个例子。添加所需的字段。

def calculate_difference
  minutes = (Date.parse("2009-06-20") - Date.today).to_i / 60
  days = minutes / (24*60)
  minutes -= days * 24*60
  hours = minutes / 60
  minutes -= hours * 60
  "#{days}d#{hours}h#{minutes}m"
end

#5


0  

I don't know of any standard, correct way to do this. As odd as it may seem the standard Ruby library has a Date class but no DateSpan functionality. Rails has a solution but it feels somewhat of a pain for me to require this whole mammoth for such a trivial task.

我不知道有什么标准,正确的方法。奇怪的是,标准Ruby库有一个Date类,但是没有DateSpan功能。Rails有一个解决方案,但对于我来说,需要这整个庞然大物来完成这样一项琐碎的任务,感觉有点痛苦。

#1


6  

Found the answer here:

在这里找到了答案:

More precise distance_of_time_in_words

更精确的distance_of_time_in_words

with this gem:

这个宝石:

https://github.com/radar/dotiw

https://github.com/radar/dotiw

#2


5  

You may be looking for distance_of_times_in_words

您可能正在寻找distance_of_times_in_words

#3


3  

There is a RubyGem which returns Time difference in a hash like {:year => 0, :month => 0,...}

有一个RubyGem,它在一个散列中返回时差,比如{:year =>,:month => 0,…}

The link is : https://rubygems.org/gems/time_diff

链接是:https://rubygems.org/gems/time_diff。

#4


1  

This is an example for difference in days, hours, seconds. Add the fields that you need.

这是天数、小时、秒的差异的一个例子。添加所需的字段。

def calculate_difference
  minutes = (Date.parse("2009-06-20") - Date.today).to_i / 60
  days = minutes / (24*60)
  minutes -= days * 24*60
  hours = minutes / 60
  minutes -= hours * 60
  "#{days}d#{hours}h#{minutes}m"
end

#5


0  

I don't know of any standard, correct way to do this. As odd as it may seem the standard Ruby library has a Date class but no DateSpan functionality. Rails has a solution but it feels somewhat of a pain for me to require this whole mammoth for such a trivial task.

我不知道有什么标准,正确的方法。奇怪的是,标准Ruby库有一个Date类,但是没有DateSpan功能。Rails有一个解决方案,但对于我来说,需要这整个庞然大物来完成这样一项琐碎的任务,感觉有点痛苦。