假设我有一个datetime对象,比如DateTime.now
。我想将小时和分钟设置为0(午夜)。我该怎么做呢?
发布于 2012-01-28 08:11:34
在Rails环境中:
多亏了ActiveSupport,你可以使用:
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"))
发布于 2011-06-13 14:55:56
不要紧,知道了。需要创建一个新的DateTime:
DateTime.new(now.year, now.month, now.day, 0, 0, 0, 0)
发布于 2011-06-13 15:27:35
如果您经常使用它,可以考虑安装这个gem来改进日期解析:
https://github.com/mojombo/chronic
require 'chronic'
Chronic.parse('this 0:00')
https://stackoverflow.com/questions/6327396
复制相似问题