Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting a date object to display a human readable date

Here's what I'd like to display:

May 13, 2012 

Here's what is being displayed:

2012-05-13 

I searched for some answers and it led me to "Formatting Dates and Floats in Ruby", where it mentions a possible solution:

<p class="date"><%= @news_item.postdate.to_s("%B %d, %Y") %></p> 

However this doesn't change the output at all. No debugging errors, or exceptions are fired.

I can do this and it works perfectly fine:

<p class="date"><%= Time.now.to_s("%B %d, %Y") %></p> 

Here is my migration file (to see what data type I used):

class CreateNewsItems < ActiveRecord::Migration   def change     create_table :news_items do |t|        t.date :postdate        t.timestamps     end   end end 
like image 207
sergserg Avatar asked Aug 06 '12 23:08

sergserg


People also ask

How do I convert a date to a readable format?

First of all, you need to create a date using your original date string. You can use d. toUTCString() instead, or a combination of functions like d. getUTCHours() and d.

How do I display a date in a specific format in HTML?

var date = new Date(); moment(date); // same as calling moment() with no args // Passing in a string date moment("12-25-1995", "MM-DD-YYYY");

How do I change the format of a date object?

String mydateStr = "/107/2013 12:00:00 AM"; DateFormat df = new SimpleDateFormat("/dMM/yyyy HH:mm:ss aa"); Date mydate = df. parse(mydateStr); Two method above can be used to change a formatted date string from one into the other. See the javadoc for SimpleDateFormat for more info about formatting codes.

How do you format a date?

The international standard recommends writing the date as year, then month, then the day: YYYY-MM-DD.


2 Answers

Date.to_s is not the same as Time.to_s. Your postdate is a Date, so therefore you might want to look at strftime instead:

postdate.strftime("%B %d, %Y") 

Or even look to add your own custom date format to your Rails app:
Need small help in converting date format in ruby

like image 73
Casper Avatar answered Sep 22 '22 06:09

Casper


The to_formatted_s function already has some common human readable formats for DateTime objects in Rails.

datetime.to_formatted_s(:db)            # => "2007-12-04 00:00:00" datetime.to_formatted_s(:short)         # => "04 Dec 00:00" datetime.to_formatted_s(:long)          # => "December 04, 2007 00:00" datetime.to_formatted_s(:long_ordinal)  # => "December 4th, 2007 00:00" datetime.to_formatted_s(:rfc822)        # => "Tue, 04 Dec 2007 00:00:00 +0000" datetime.to_formatted_s(:iso8601)       # => "2007-12-04T00:00:00+00:00" 
like image 34
FernandoEscher Avatar answered Sep 18 '22 06:09

FernandoEscher