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
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With