我得把时间从这个格式转换成这个
例如: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方法来优雅地完成这项工作。我试过了,可以单独设置日期和时间的格式,但不能按照我想要的格式一起设置。有人能指出我的格式的用法吗

最佳答案

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

关于ruby - Ruby日期和时间从一种格式转换为另一种格式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29503257/

10-10 23:45
查看更多