Cy. Cy. - 7 months ago 11
Ruby Question

Convert text string to any valid Ruby formatted time

I have the following date string "Monday 31 January".

Is there any way to convert that to a valid Ruby formatted time so I can convert it to something else?




How could I parse it in the case that it was in a different language, for instance in Spanish "Lunes 31 Enero"?

Answer

How could I parse it in the case that it was in a different language, i.e. Spanish "Lunes 31 Enero"?

Normally I'd say go with the Chronic gem as your best bet for flexible date time parsing. Tossing in different languages makes it a different problem, because the libraries are geared toward English.

That means falling back to Date.parse. Dropping into IRB I had a surprise:

ruby-1.9.2-p136 :001 > require 'date'
 => true 
ruby-1.9.2-p136 :002 > puts Date.parse('Lunes 31 Enero')
2011-01-31

So, Date.parse is already Spanish-saavy.

If it wasn't, it might be possible to override Date's Month and Day constants to give it a helping hand:

require 'date'

Date::MONTHNAMES      = [nil] + %w( Enero Febrero Marzo Abril Mayo Junio Julio Agosto Septiembre Octubre Noviembre Diciembre )
Date::DAYNAMES        = %w( Lunes Martes Miércoles Jueves Viernes Sábado Domingo )
Date::ABBR_MONTHNAMES = [nil] + %w( Ene Feb Mar Abr May Jun Jul Ago Sep Oct Nov Dic )
Date::ABBR_DAYNAMES   = %w( Lun Mar Mié Jue Vie Sáb Dom )

I haven't tested that, since it already works without messing with things, but for other, non-supported, languages, it might be a worthwhile experiment to change the values and see what happens.

Comments