Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change string in a date format to another format

Tags:

date

ruby

I have a string like this (YYYYMMDD):

20120225

And I want to have a string like this (MM/DD/YYYY):

02/25/2012

What's a good way of doing this in Ruby? I have thought about converting the first string to a Date, and then change the format. Or just treating the string and getting the parts I want and build the new string.

like image 363
Hommer Smith Avatar asked Mar 10 '12 19:03

Hommer Smith


2 Answers

Parsing it then formatting it is the best solution:

Date.parse("20120225").strftime("%m/%d/%Y")  #=> "02/25/2012"
like image 142
Andrew Marshall Avatar answered Oct 07 '22 13:10

Andrew Marshall


strptime parses the string representation of date with the specified template and creates a date object.

Date.strptime('20120225', '%Y%m%d').strftime("%m/%d/%Y")  #=> "02/25/2012"
like image 21
Sandip Ransing Avatar answered Oct 07 '22 12:10

Sandip Ransing