Change the string in date format to a different format

I have a line like this (YYYYMMDD):


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


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.


source to share

4 answers

Parsing , formatting is the best solution

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




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"




Just for fun, how about:





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.



All Articles