Ruby-on-rails 你如何从日期时间中减去?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3314462/
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:56:56  来源:igfitidea点击:

How do you subtract from a datetime?

ruby-on-railsrubydatetime

提问by Trip

I'd like to write a simple function to say in hours:

我想写一个简单的函数,以小时为单位:

How much time has passed since this has been created?

自创建以来已经过去了多少时间?

My attempts:

我的尝试:

-time = DateTime.now.hour - (self.created_at.hour)

Does anyone know how to do this in Ruby on Rails?

有谁知道如何在 Ruby on Rails 中做到这一点?

回答by mckeed

Rails usually uses Time, not DateTime. Why don't you do Time.now - self.created_at? Then you can convert from seconds to hours by dividing by 3600.

Rails 通常使用Time,而不是DateTime. 你为什么不做Time.now - self.created_at?然后您可以通过除以 3600 将秒转换为小时。

回答by Trip

Got it!. First you have to make sure your data is in the same data it will be subtracted from whether its a Time or a DateTime. I chose time. Then you divide it by Ruby's built in time methods. This translates into how many days, but it can also be, 1.hour. etc.

知道了!。首先,您必须确保您的数据与从时间或日期时间中减去的数据相同。我选择了时间。然后你将它除以 Ruby 的内置时间方法。这转化为多少天,但也可以是 1.hour。等等。

(Time.now - self.created_at.to_time)/1.day

回答by sosborn

You are looking for the time_ago_in_words(from_time, include_seconds = false) function. Here are some examples from the docs:

您正在寻找 time_ago_in_words(from_time, include_seconds = false) 函数。以下是文档中的一些示例:

time_ago_in_words(3.minutes.from_now)       # => 3 minutes
time_ago_in_words(Time.now - 15.hours)      # => 15 hours
time_ago_in_words(Time.now)                 # => less than a minute
from_time = Time.now - 3.days - 14.minutes - 25.seconds     # => 3 days