Ruby-on-rails 如何在 Rails 中将当前时间添加 10 天

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

How to add 10 days to current time in Rails

ruby-on-railsdatetimeruby-on-rails-3activesupport

提问by Yuval Karmi

I tried doing something like

我尝试做类似的事情

Time.now + 5.days

but that doesn't work, even though I vaguely remember seeing, and being very impressed, with being able to do something like 2.yearsetc.

但这不起作用,即使我依稀记得看到并印象深刻,能够做类似的事情2.years

How do I do that in Rails 3?

我如何在 Rails 3 中做到这一点?

回答by gunn

Use

Time.now + 10.days

or even

甚至

10.days.from_now

Both definitely work. Are you sure you're in Rails and not just Ruby?

两者绝对有效。你确定你使用的是 Rails 而不仅仅是 Ruby?

If you definitely are in Rails, where are you trying to run this from? Note that Active Support has to be loaded.

如果你肯定在 Rails 中,你想从哪里运行它?请注意,必须加载 Active Support。

回答by Jonathan Julian

days, years, etc., are part of Active Support, So this won't work in irb, but it should work in rails console.

daysyears等是 Active Support 的一部分,因此这在 中不起作用irb,但在 中应该起作用rails console

回答by dj kaori

This definitely works and I use this wherever I need to add days to the current date:

这绝对有效,我在需要为当前日期添加天数的任何地方使用它:

Date.today() + 5

回答by Hieu Pham

Some other options, just for reference

其他一些选择,仅供参考

-10.days.ago
# Available in Rails 4
DateTime.now.days_ago(-10)

Just list out all options I know:

只需列出我知道的所有选项:

[1] Time.now + 10.days
[2] 10.days.from_now
[3] -10.days.ago
[4] DateTime.now.days_ago(-10)
[5] Date.today + 10

So now, what is the difference between them if we care about the timezone:

那么现在,如果我们关心时区,它们之间有什么区别:

  • [1, 4]With system timezone
  • [2, 3]With config timezone of your Rails app
  • [5]Date only no time included in result
  • [1, 4]带系统时区
  • [2, 3]使用 Rails 应用程序的配置时区
  • [5]结果中只包含日期不包含时间

回答by Rahul Patel

Try this on Rails

在 Rails 上试试这个

Time.new + 10.days 

Try this on Ruby

在 Ruby 上试试这个

require 'date'
DateTime.now.next_day(10).to_time

回答by Ramyani

Try this on Ruby. It will return a new date/time the specified number of days in the future

在 Ruby 上试试这个。它将返回未来指定天数的新日期/时间

DateTime.now.days_since(10)