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
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.
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");
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.
The international standard recommends writing the date as year, then month, then the day: YYYY-MM-DD.
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
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"
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