Set time part of DateTime in ruby

Solution 1:

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:

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

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

Solution 3:

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.