Change the string in date format to a different format

I have a line like this (YYYYMMDD):

20120225

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

02/25/2012

What's a good way to do this in Ruby? I thought about converting the first string to a date and then changed the format. Or just process the string and get the parts you want and create a new string.

+3


source to share


4 answers


Parsing , formatting is the best solution



Date.parse("20120225").strftime("%m/%d/%Y")  #=> "02/25/2012"

      

+13


source


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



Date.strptime('20120225', '%Y%m%d').strftime("%m/%d/%Y")  #=> "02/25/2012"

      

+8


source


Just for fun, how about:

'20120225'.unpack('A4A2A2').rotate.join('/')

      

+4


source


This is possible with regular expressions:

s1 = '20120225'
s2 = "$2/$3/$1" if s1 =~ /(\d{4})(\d{2})(\d{2})/

      

Or, if you are sure of the format of your string and have performance issues, I believe the best solution is

s2 = s1[4..5] + '/' + s1[6..7] + '/' + s1[0..3]

      

But if you don't have performance requirements, I think Andrew Marshall's solution is better because it checks the validity of the date.

+1


source







All Articles