Change string in a date format to another format

前端 未结 4 1882
独厮守ぢ
独厮守ぢ 2021-01-03 04:42

I have a string like this (YYYYMMDD):

20120225

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

02/25/

相关标签:
4条回答
  • 2021-01-03 05:09

    Just for fun how about:

    '20120225'.unpack('A4A2A2').rotate.join('/')
    
    0 讨论(0)
  • 2021-01-03 05:17

    Parsing it then formatting it is the best solution:

    Date.parse("20120225").strftime("%m/%d/%Y")  #=> "02/25/2012"
    
    0 讨论(0)
  • 2021-01-03 05:30

    It's possible with regular expressions:

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

    Or if you're sure of the format of your string and have performance issues, I think the best solution is

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

    But if you have no performance needs, I think the solution of Andrew Marshall is better because it checks the date validity.

    0 讨论(0)
  • 2021-01-03 05:32

    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"
    
    0 讨论(0)
提交回复
热议问题