代码之家  ›  专栏  ›  技术社区  ›  Vishal Goel

如何避免在Ruby中存储数组中的日期对象?

  •  1
  • Vishal Goel  · 技术社区  · 7 年前

    考虑下面的代码:

    dates = ["20th OCT 1232", "6th JUN 2019", "23th AUG 2017", "9th JAN 2015"]
    
    def reformateDate(dates)
        ans = []
        dates.length.times do |i|
            ans << (DateTime.parse(dates[i], '%d %b %Y').to_date)
        end
        ans
    end
    

    此函数返回以下格式的数组:

    [#<Date: 1232-10-20 ((2171339j,0s,0n),+0s,2299161j)>, #<Date: 2019-06-06 ((2458641j,0s,0n),+0s,2299161j)>, #<Date: 2017-08-23 ((2457989j,0s,0n),+0s,2299161j)>, #<Date: 2015-01-09 ((2457032j,0s,0n),+0s,2299161j)>]
    

    但我希望它以这种格式返回数组:

    ["1232-10-20","2019-06-06","2017-08-23","2015-01-09"]
    

    那我该怎么做呢?

    3 回复  |  直到 7 年前
        1
  •  4
  •   iGian    7 年前
    dates.map { |e| Date.parse(e).strftime('%Y-%m-%d') }
    #=> ["1232-10-20", "2019-06-06", "2017-08-23", "2015-01-09"]
    

    更改模板 '%Y-%m-%d' 根据您的需要,请参阅: Date#strftime .


    从卡里·斯沃夫兰那里得到明智的建议。

    而不是 Date.parse(e) 你可以用 Date.strptime(e, '%dth %b %Y') ,或多或少与strftime相反。看到了吗 Date#strptime . 它遵循一个模板( '%dth %b %Y' th 到模板之后 %d

    Date.strptime("20th OCT 1232", '%dth %b %Y') #=> #<Date: 1232-10-20 ((2171339j,0s,0n),+0s,2299161j)>
    

    '1st OCT 2018' '23rd OCT 2018' ? 模板不匹配,因为它希望找到 st rd .

    ,手牵手的方法 String#sub :

    "20th OCT 1232".sub(/(?<=\d)\p{Alpha}+/, '') #=> "20 OCT 1232"
    

    所以,混合在一起,最好的安全解决方案应该是:

    dates.map { |e| Date.strptime(e.sub(/(?<=\d)\p{Alpha}+/, ''), '%d %b %Y').strftime('%Y-%m-%d') }
    
        2
  •  2
  •   Renzo Tissoni    7 年前

    实际上,你在写的时候是在存储日期对象:

    ans << (DateTime.parse(dates[i], '%d %b %Y').to_date)

    这有几个问题:首先,括号不起任何作用,所以可以删除它们。其次,您要做的是将字符串解析为DateTime对象,然后将其转换为Date对象。我不知道你为什么要这么做,但我相信这是个错误。如果希望通过时间使用DATETIME对象将其转换为字符串,请考虑使用 strftime ,它将获取DateTime对象并将其转换为具有特定格式的字符串。它看起来是这样的:

    ans << DateTime.parse(dates[i], '%d %b %Y').strftime('%Y-%m-%d')

        3
  •  1
  •   spickermann    7 年前

    require 'date'
    
    def reformat_date(dates)
      dates.map { |date| Date.parse(date).to_s }
    end
    
    dates = ["20th OCT 1232", "6th JUN 2019", "23th AUG 2017", "9th JAN 2015"]
    reformat_date(dates)
    #=> ["1232-10-20", "2019-06-06", "2017-08-23", "2015-01-09"]
    
    推荐文章