如何在 Rails 中将当前时间添加 10 天
我尝试做类似的事情,
Time.now + 5.days
但这不起作用,尽管我隐约记得看到过,并且印象非常深刻,能够做类似 2.years 等的事情。
我如何在 Rails 中做到这一点3?
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.years
etc.
How do I do that in Rails 3?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
使用
甚至
两者都肯定有效。您确定您使用的是 Rails 而不仅仅是 Ruby 吗?
如果你确实在 Rails 中,你想从哪里运行它?请注意,必须加载 Active Support。
Use
or even
Both definitely work. Are you sure you're in Rails and not just Ruby?
If you definitely are in Rails, where are you trying to run this from? Note that Active Support has to be loaded.
days
、years
等是 Active Support 的一部分,因此这在irb
中不起作用,但应该在中起作用>rails 控制台
。days
,years
, etc., are part of Active Support, So this won't work inirb
, but it should work inrails console
.其他一些选项,仅供参考
只需列出我所知道的所有选项:
那么现在,如果我们关心时区,它们之间有什么区别:
[1, 4]
使用系统时区[ 2, 3]
使用 Rails 应用程序的配置时区[5]
结果中仅包含日期,不包含时间Some other options, just for reference
Just list out all options I know:
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这绝对有效,只要我需要在当前日期上添加天数,我就会使用它:
This definitely works and I use this wherever I need to add days to the current date:
在 Rails 上尝试这个
在 Ruby 上尝试这个
Try this on Rails
Try this on Ruby
在 Ruby 上试试这个。
它将返回指定天数后的新日期/时间
Try this on Ruby.
It will return a new date/time the specified number of days in the future
之间有一点区别:
Time.now + 10.days
3.0.1 :003 >
日期.今天 + 1.天
=> 2022 年 12 月 14 日星期三
或什至
10.days.from_now
3.0.1 :002 >
1.day.from_now
=> 2022-12-14 15:49:57.35305172 +0600
Little bit difference between:
Time.now + 10.days
3.0.1 :003 >
Date.today + 1.day
=> Wed, 14 Dec 2022
or even
10.days.from_now
3.0.1 :002 >
1.day.from_now
=> 2022-12-14 15:49:57.35305172 +0600