Rails DateTime.now without Time

Ruby on-RailsRubyDatetime

Ruby on-Rails Problem Overview


I need to use DateTime.now to grab the current date, and "strip off" the time.

For example, this shows what I don't want: DateTime.now => Sat, 19 Nov 2011 18:54:13 UTC +00:00

This shows what I do want: DateTime.now.some_operation => 2011-11-06 00:00:00 UTC

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

You can use one of the following:

  • DateTime.current.midnight
  • DateTime.current.beginning_of_day
  • DateTime.current.to_date

Solution 2 - Ruby on-Rails

What you need is the function strftime:

Time.now.strftime("%Y-%d-%m %H:%M:%S %Z")

Solution 3 - Ruby on-Rails

What about Date.today.to_time?

Solution 4 - Ruby on-Rails

You can use just:

Date.current

Solution 5 - Ruby on-Rails

If you're happy to require 'active_support/core_ext', then you can use

DateTime.now.midnight # => Sat, 19 Nov 2011 00:00:00 -0800

Solution 6 - Ruby on-Rails

If you want today's date without the time, just use Date.today

Solution 7 - Ruby on-Rails

Figured it out. This works:

DateTime.now.in_time_zone.midnight

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
QuestionMikeView Question on Stackoverflow
Solution 1 - Ruby on-RailsIgor KapkovView Answer on Stackoverflow
Solution 2 - Ruby on-RailsVP.View Answer on Stackoverflow
Solution 3 - Ruby on-RailsErnestoView Answer on Stackoverflow
Solution 4 - Ruby on-RailsVlad HilkoView Answer on Stackoverflow
Solution 5 - Ruby on-RailsJon MView Answer on Stackoverflow
Solution 6 - Ruby on-RailsLordKizView Answer on Stackoverflow
Solution 7 - Ruby on-RailsMikeView Answer on Stackoverflow