将字符串日期格式从“17-Nov-2011”转换为到“11/17/11”

问题描述:

我有这个代码将日期字符串数组从2011年11月17日的格式转换为11/17/11:

I have this code that converts an array of date strings from a format of 17-Nov-2011 to 11/17/11:

def date_convert dates
  months = { 'Jan' => 1, 'Feb' => 2, 'Mar' => 3, 'Apr' => 4, 
             'May' => 5, 'Jun' => 6, 'Jul' => 7, 'Aug' => 8, 
             'Sep' => 9, 'Oct' => 10, 'Nov' => 11, 'Dec' => 12 }
  new_dates = []
  dates.each do |date|
    date_split = date.split('-')
    month = months[date_split[1]] 
    day = date_split[0]
    year = date_split[2][-2, 2]
    new_dates.push ("#{month}/#{day}/#{year}")
  end
  new_dates
end

有没有更好的,可能内置的方法来使用Ruby进行这种转换?我正在学习Ruby,所以任何其他的方法,将不胜感激。

Is there a better, possibly built in, way to make this conversion with Ruby? I am learning Ruby so any other approach to this would be much appreciated.

使用内置 Time.parse Time#strftime 函数

Use the built-in Time.parse and Time#strftime functions.

require 'time'
time = Time.parse("17-Nov-2011")
time.strftime("%m/%d/%y")
# => "11/17/11"