代码之家  ›  专栏  ›  技术社区  ›  Qumber Ali

如何在rails上将日期格式从mm/dd/yyy更改为dd/mm/yyyy ruby

  •  -4
  • Qumber Ali  · 技术社区  · 6 年前

    我的日期是:

    2018年1月14日

    我想把它改成:

    2018年1月14日或2018年1月14日

    3 回复  |  直到 6 年前
        1
  •  3
  •   Jagdeep Singh    6 年前

    两个步骤:

    • 您需要将字符串转换为 Date 反对。为此,使用 Date#strptime 是的。
    • 你可以用 Date#strftime 转换 日期 对象转换为首选格式。

    见以下实施:

    str = '01/14/2018'
    
    date = Date.strptime(str, '%m/%d/%Y')
     => #<Date: 2018-01-14 ((2458133j,0s,0n),+0s,2299161j)>
    
    date.strftime('%d-%m-%Y')
     => "14-01-2018"
    
    date.strftime('%Y-%m-%d')
     => "2018-01-14"
    
        2
  •  2
  •   Cary Swoveland    6 年前

    这是一个螺母和螺栓串操作问题。我们可以将字符串转换为日期对象,然后将这些对象转换回具有给定格式的字符串,但是简单地使用字符串方法似乎更简单,如我在下面所做的。

    我们得到了日期字符串

    str = "01/14/2018"
    

    并将使用

    str_fmt = "%s-%s-%s"
    

    作为格式字符串。

    最简单的方法是使用 方法 String#[] 是的。

    str_fmt % [str[3,2], str[0,2], str[6,4]]
      #=> "14-01-2018"
    str_fmt % [str[6,4], str[0,2], str[3,2]]
      #=> "2018-01-14"
    

    或者,可以将正则表达式用于月、日和年的捕获组。

    r = /
        \A       # match the beginning of the string
        (\d{2})  # match two digits in capture group 1
        \/       # match a forward slash
        (\d{2})  # match two digits in capture group 2
        \/       # match a forward slash
        (\d{4})  # match two digits in capture group 3
        \z       # match the end of the string
        /x       # free-spacing regex definition mode
    
    str =~ r
    str_fmt % [$2, $1, $3]
      #=> "14-01-2018"
    str_fmt % [$3, $1, $2]
      #=> "2018-01-14"
    

    如果要使用命名捕获组,我们将编写以下内容。

    m = str.match /\A(?<mon>\d{2})\/(?<day>\d{2})\/(?<yr>\d{4})\z/
    str_fmt % [m[:day], m[:mon], m[:yr]]
      #=> "14-01-2018"
    str_fmt % [m[:yr], m[:mon], m[:day]]
      #=> "2018-01-14"
    
        3
  •  0
  •   TANMAYA    6 年前
    '01/14/18'.split('/').rotate(-1).reverse.join('-')