在 Ruby 中设置 DateTime 的 time 部分

假设我有一个日期时间对象,例如 DateTime.now。我想把小时和分钟设置为0(午夜)。我该怎么做?

85081 次浏览

Nevermind, got it. Need to create a new DateTime:

DateTime.new(now.year, now.month, now.day, 0, 0, 0, 0)

如果你经常使用它,可以考虑安装这个 gem 来改进日期解析:

https://github.com/mojombo/chronic

require 'chronic'


Chronic.parse('this 0:00')

在 Rails 环境中:

Thanks to ActiveSupport you can use:

DateTime.now.midnight
DateTime.now.beginning_of_day

或者

DateTime.now.change({ hour: 0, min: 0, sec: 0 })


# More concisely
DateTime.now.change({ hour: 0 })

在纯 Ruby 环境中:

now = DateTime.now
DateTime.new(now.year, now.month, now.day, 0, 0, 0, now.zone)

或者

now = DateTime.now
DateTime.parse(now.strftime("%Y-%m-%dT00:00:00%z"))

警告 : DateTime.now.midnightDateTime.now.beginning_of_day返回相同的值(这是当前一天的零点——午夜不会返回24:00:00,正如您期望从它的名称中得到的那样)。

所以我添加这个作为进一步的信息,任何人谁可能使用接受的答案来计算午夜 x 天在未来。

For example, a 14 day free trial that should expire at midnight on the 14th day:

DateTime.now.midnight + 14.days

是第14天的早晨,相当于13.x 天的试用期(x 是一天中剩下的部分——如果现在是中午,那么就是13.5天的试用期)。

你实际上需要这样做:

DateTime.now.midnight + 15.days

在第14天的午夜。

由于这个原因,我总是更喜欢使用 beginning_of_day,因为它是00:00:00。使用午夜可能会误导/误解。