Set time part of DateTime in ruby

RubyDatetime

Ruby Problem Overview


Say I have a datetime object eg DateTime.now. I want to set hours and minutes to 0 (midnight). How can I do that?

Ruby Solutions


Solution 1 - Ruby

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"))

Solution 2 - Ruby

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

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

Solution 3 - Ruby

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.

Solution 4 - Ruby

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')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJesse AldridgeView Question on Stackoverflow
Solution 1 - RubyashodaView Answer on Stackoverflow
Solution 2 - RubyJesse AldridgeView Answer on Stackoverflow
Solution 3 - RubyrmcsharryView Answer on Stackoverflow
Solution 4 - RubywizztjhView Answer on Stackoverflow