Change string in a date format to another format

前端 未结 4 1881
独厮守ぢ
独厮守ぢ 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: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.

提交回复
热议问题