Kerozu
Kerozu

Reputation: 673

Format date without whitespace in Rails

API that I use returns date as "20090320" which is Y, m and d.

How can I format it in rails to have for example 20-03-2009?

Thanks in advance!

Upvotes: 5

Views: 989

Answers (4)

Arup Rakshit
Arup Rakshit

Reputation: 118261

Do as below using Date::parse and Date#strftime:

require 'date'
d = Date.parse "20090320" # => #<Date: 2009-03-20 ((2454911j,0s,0n),+0s,2299161j)> 
d.strftime('%d-%m-%Y') # => "20-03-2009" 

In one line write as

Date.parse("20090320").strftime('%d-%m-%Y')

Upvotes: 6

Roman Kiselenko
Roman Kiselenko

Reputation: 44360

in rails you can use to_date:

"20090320".to_date
=> Fri, 20 Mar 2009
"20090320".to_date.strftime("%d-%m-%Y")
=> "20-03-2009"

Upvotes: 5

Kyle Decot
Kyle Decot

Reputation: 20815

The method's that you're looking for are parse and strftime on the Date class.

You'll need to require date from the ruby standard library for this to work though.

Here is an example

require 'date'

puts Date.parse("20090320").strftime("%d-%m-%Y") # 20-03-2009

Upvotes: 0

Utsav Kesharwani
Utsav Kesharwani

Reputation: 1745

Date.strptime('20090320', '%Y%m%d').strftime('%d-%m-%Y')

Upvotes: 9

Related Questions