Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails DateTime.now without Time

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

like image 996
Mike Avatar asked Nov 19 '11 18:11

Mike


People also ask

What is the use of currentTime in rails?

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

Is it possible to use date class in rails?

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.

What is the difference between date and DateTime in Ruby?

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.

What are the limitations of the time class in Ruby on rails?

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.


3 Answers

You can use one of the following:

  • DateTime.current.midnight
  • DateTime.current.beginning_of_day
  • DateTime.current.to_date
like image 91
Igor Kapkov Avatar answered Oct 05 '22 00:10

Igor Kapkov


What you need is the function strftime:

Time.now.strftime("%Y-%d-%m %H:%M:%S %Z")
like image 42
VP. Avatar answered Oct 05 '22 00:10

VP.


You can use just:

Date.current
like image 43
Vlad Hilko Avatar answered Oct 04 '22 22:10

Vlad Hilko