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
Use (Date)Time.current instead of (Date)Time.now Rails extends the Time and DateTime objects, and includes the current property for retrieving the time the Rails environment is set to (default = UTC), as opposed to the server time (Could be anything).
For most cases, the Time with the time zone class from Rails’ ActiveSupport is sufficient. But sometimes, when you just need a string format of year, month and day, Dateclass still worth a try. Remember to add require 'date'when you encounter undefined methoderror, when trying to use Dateclass.
Date and DateTime classes are both from date library. And Time class from its own time library. Tech Notes from Steven Home About Date, Time, DateTime in Ruby and Rails Mar 23, 2013• Steven Yue There are 3 different classes in Ruby that handle date and time. Dateand DateTimeclasses are both from datelibrary. And Timeclass from its own timelibrary.
Firstly, it can only represent dates between 1970 and 2038 ( since Ruby v1.9.2, it can represent date from 1823-11-12 to 2116-02-20 ). Secondly, the time zone is limited to UTC and the system’s local time zone in ENV['TZ']. Rails provide a really good time class called ActiveSupport::TimeWithZone.
You can use one of the following:
DateTime.current.midnight
DateTime.current.beginning_of_day
DateTime.current.to_date
What you need is the function strftime:
Time.now.strftime("%Y-%d-%m %H:%M:%S %Z")
You can use just:
Date.current
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With