ruby - 将字符串日期格式从 "17-Nov-2011"转换为 "11/17/11"

标签 ruby date formatting

我有这段代码可以将日期字符串数组从 17-Nov-2011 格式转换为 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,因此非常感谢任何其他方法。

最佳答案

使用内置的 Time.parseTime#strftime 函数。

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

关于ruby - 将字符串日期格式从 "17-Nov-2011"转换为 "11/17/11",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8171921/

相关文章:

java - 如何在java中将当前时间添加到上一个日期?

java - 如果两个日期相等,则 Date before 方法返回 false

json - 如何在 Visual Studio Community 2019 中格式化 JSON 文档?

mysql - Ruby 搜索多个字段

ruby-on-rails - rails 在生产服务器中包含 CarrierWave::RMagick 错误

ruby - 如何通过多字段对ruby中的数组进行排序

date - 检查日期范围与其他一些日期范围之间的缺失天数

formatting - Gnuplot 平滑置信区间线而不是误差线

xaml - WinRT 中的当前文化是错误的

ruby-on-rails - Ruby .each 效率