s c
s c

Reputation: 71

convert 'dates' in different formats to a specific format in ruby

I have arrays as below:

date_val = ['12-20-1986', '23-01-2013', '2013-01-01', '12/01/2013', '23/12/1980']
formats = ['mm-dd-yyyy', 'dd-mm-yyyy', 'yyyy-dd-mm', 'mm/dd/yyyy', 'dd/mm/yyyy']

where the array formats is showing the format in which array date_val is storing values.

I am executing a loop in which one by one all the values will come and i need to convert the values in the array date_val to the required_format

required_format = 'yyyy-mm-dd'

Upvotes: 1

Views: 56

Answers (1)

Eric Duminil
Eric Duminil

Reputation: 54293

'yyyy-mm-dd' isn't a valid strpfime format. You need to convert it ('%Y-%m-%d') first :

require 'date'

date_val = ['12-20-1986', '23-01-2013', '2013-01-01', '12/01/2013', '23/12/1980']
formats = ['mm-dd-yyyy', 'dd-mm-yyyy', 'yyyy-dd-mm', 'mm/dd/yyyy', 'dd/mm/yyyy']
required_format = 'yyyy-mm-dd'

def to_strf_format(mmddyyyy)
  mmddyyyy.sub('yyyy','%Y').sub('dd','%d').sub('mm','%m')
end

new_date_vals = date_val.zip(formats).map do |date_str, mmddyyyy|
  date = Date.strptime(date_str, to_strf_format(mmddyyyy))
  date.strftime(to_strf_format(required_format))
end

p new_date_vals
#=> ["1986-12-20", "2013-01-23", "2013-01-01", "2013-12-01", "1980-12-23"]

Upvotes: 4

Related Questions