在 Ruby 中减去日期并获得以分钟为单位的差异

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2852605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:41:10  来源:igfitidea点击:

Subtract dates in Ruby and get the difference in minutes

ruby-on-railsrubydate

提问by Mark

how do i subtract two different UTC dates in Ruby and then get the difference in minutes?

我如何在 Ruby 中减去两个不同的 UTC 日期,然后得到以分钟为单位的差异?

Thanks

谢谢

采纳答案by Chubas

(time1 - time2) / 60

(时间 1 - 时间 2) / 60

If the time objects are string, Time.parse(time)them first

如果时间对象是字符串,Time.parse(time)它们首先

回答by Alex Korban

If you subtract two Date or DateTime objects, the result is a Rational representing the number of days between them. What you need is:

如果将两个 Date 或 DateTime 对象相减,则结果是一个 Rational,表示它们之间的天数。你需要的是:

a = Date.new(2009, 10, 13) - Date.new(2009, 10, 11)
(a * 24 * 60).to_i   # 2880 minutes

or

或者

a = DateTime.new(2009, 10, 13, 12, 0, 0) - DateTime.new(2009, 10, 11, 0, 0, 0)
(a * 24 * 60).to_i   # 3600 minutes

回答by user2295540

https://rubygems.org/gems/time_difference- Time Difference gem for Ruby

https://rubygems.org/gems/time_difference- Ruby 的时差 gem

start_time = Time.new(2013,1)
end_time = Time.new(2014,1)
TimeDifference.between(start_time, end_time).in_minutes

回答by techdreams

Let's say you have two dates task_signed_inand task_signed_outfor a simple @userobject. We could do like this:

假设您有两个日期task_signed_intask_signed_out一个简单的@user对象。我们可以这样做:

(@user.task_signed_out.to_datetime - @user.task_signed_in.to_datetime).to_i

This will give you result in days. Multiply by 24you will get result in hours and again multiply by 60you will result in minutes and so on.

这将在几天内为您提供结果。乘以24您将得到数小时的结果,再次乘以您将得到60数分钟,依此类推。

This is the most up to date solution tested in ruby 2.3.x and above.

这是在 ruby​​ 2.3.x 及更高版本中测试的最新解决方案。