【问题标题】:Ruby date and time conversion from one format to otherRuby 日期和时间从一种格式到另一种格式的转换
【发布时间】:2015-06-12 17:43:39
【问题描述】:

我必须把时间从这个格式转换成这个 例如:02/16/2015:19:16:07 #=> 20150216191607 我写过这样的代码:

def convert_date(old_date)
    new_date = old_date[6..9] + old_date[0..1]+old_date[3..4]+old_date[11..12]+old_date[14..15] + old_date[17..18]
    return new_date
end

但我听说过 ruby​​ 中的 Time 和 Date 类,它们提供了 parse 和 strftime 方法来优雅地完成这项工作。我试过了,可以单独格式化日期和时间,但不能以我想要的格式组合在一起。有人可以指出我的格式的用法

【问题讨论】:

    标签: ruby time format


    【解决方案1】:
    require 'date'
    
    def convert_date(old_date)
      DateTime.strptime(old_date, '%m/%d/%Y:%H:%M:%S').strftime("%Y%m%d%H%M%S")
    end
    
    convert_date('02/16/2015:19:16:07')   
      #-> 20150216191607
    

    【讨论】:

    • 谢谢卡里!不知道日期时间
    • 注意DateTime.superclass #=> Date。你可以改写require 'time'; Time.strptime....`.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-23
    • 2015-04-23
    相关资源
    最近更新 更多