Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a string date format from "17-Nov-2011" to "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

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.

like image 708
Sean Lerner Avatar asked Nov 17 '11 17:11

Sean Lerner


1 Answers

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"
like image 51
Simone Carletti Avatar answered Nov 30 '22 05:11

Simone Carletti