Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 609
Kerozu Avatar asked Jan 26 '14 14:01

Kerozu


3 Answers

Date.strptime('20090320', '%Y%m%d').strftime('%d-%m-%Y')
like image 51
Utsav Kesharwani Avatar answered Oct 16 '22 15:10

Utsav Kesharwani


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')
like image 34
Arup Rakshit Avatar answered Oct 16 '22 15:10

Arup Rakshit


in rails you can use to_date:

"20090320".to_date
=> Fri, 20 Mar 2009
"20090320".to_date.strftime("%d-%m-%Y")
=> "20-03-2009"
like image 5
Philidor Avatar answered Oct 16 '22 15:10

Philidor