AbstractBrain Answers About us

Convert DateTime into Date in Ruby on Rails

Question

How can I transform a DateTime into a Date in Ruby on Rails?

In a Ruby on Rails application I have the created_at column.

Now I want to print it:

Posted on <%= @post.created_at.to_formatted_s(:short) %>

However that prints something like Posted on 05 Dec 12:34, which includes the time.

Is it possible to have only the date (without time)?

Answer

You can simply call `to_date` to convert a DateTime object into a Date in Ruby on Rails.

For example:

@post.created_at.to_formatted_s(:short)
# => "10 Nov 12:34"

@post.created_at.to_date.to_formatted_s(:short)
# => "10 Nov"