Set temporary part of DateTime to ruby

Say I have a datetime object like DateTime.now . I want to set the hours and minutes to 0 (midnight). How can i do this?

+71
ruby datetime
Jun 13 2018-11-11T00:
source share
4 answers

In the 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 pure 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")) 
+170
Jan 28 2018-12-12T00:
source share

Nevermind, understood. You need to create a new DateTime:

 DateTime.new(now.year, now.month, now.day, 0, 0, 0, 0) 
+32
Jun 13 2018-11-11T00:
source share

If you use it often, consider installing this gem to improve date parsing:

https://github.com/mojombo/chronic

 require 'chronic' Chronic.parse('this 0:00') 
+3
Jun 13 '11 at 7:27
source share

Warning : DateTime.now.midnight and DateTime.now.beginning_of_day return the same value (this is the zero hour of the current day - midnight does not return at 24:00:00, as one would expect from his name).

So, I am adding this as additional information for those who can use the accepted answer to calculate the midnight x days in the future.

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

 DateTime.now.midnight + 14.days 

- This is the morning of the 14th day, which is equivalent to the 13-day test (x is the part of the day remaining until the end - if it is noon, then this is a 13.5-day trial version).

You really 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 it is 00:00:00. Using midnight can be misleading / misunderstood.

+2
Apr 13 '16 at 11:05
source share



All Articles