开发者

Set time part of DateTime in ruby

开发者 https://www.devze.com 2023-03-13 01:15 出处:网络
Say I have a datetime object eg DateTime.now.I want to set hours and minutes to 0 (midnight).How can I开发者_如何学编程 do that?Within a Rails environment:

Say I have a datetime object eg DateTime.now. I want to set hours and minutes to 0 (midnight). How can I开发者_如何学编程 do that?


Within a Rails environment:

Thanks to ActiveSupport you can use:

DateTime.now.midnight
DateTime.now.beginning_of_day

OR

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

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

Within a purely Ruby environment:

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

OR

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


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

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


Warning: DateTime.now.midnight and DateTime.now.beginning_of_day return the same value (which is the zero hour of the current day - midnight does not return 24:00:00 as you would expect from its name).

So I am adding this as further info for anyone who might use the accepted answer to calculate midnight x days in the future.

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

DateTime.now.midnight + 14.days

is the morning of the 14th day, which equates to a 13.x day trial (x is the part of the day left over - if now is noon, then it's 13.5 day trial).

You would actually need to do this:

DateTime.now.midnight + 15.days

to get midnight on the 14th day.

For this reason I always prefer to use beginning_of_day, since that is 00:00:00. Using midnight can be misleading/misunderstood.


If you use it often consider install this gem to improve date parse:

https://github.com/mojombo/chronic

require 'chronic'

Chronic.parse('this 0:00')
0

精彩评论

暂无评论...
验证码 换一张
取 消