Ruby 日期和时间从一种格式转换为另一种格式
Ruby date and time conversion from one format to other
我必须将时间从这种格式转换成这种格式
例如: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 中的时间和日期 class 提供了 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
我必须将时间从这种格式转换成这种格式 例如: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 中的时间和日期 class 提供了 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