Tuesday, November 27, 2007

Parsing time in custom format in Ruby

I am sure you have used Time#strftime (or Date, DateTime) to format your date/time into your own custom format for pretty time display. This is fine and great. But how do you parse a date or time in your own specific format in Ruby?

There is a little method called DateTime#strptime. Its second parameter takes a string, containing basically all the options available to you in Time#strftime (eg. %m-%d-%Y) and return you a DateTime object. This method is strangely not available in Time class. Fortunately from there you can use the Rails methods #to_time to convert to the Time object you want.


  DateTime.strptime("12/25/2007 01:00 AM EST", "%m/%d/%Y %I:%M %p %Z")


Anonymous said...

DateTime.strptime("12/25/2007 01:00 AM EST", "%m/%d/%Y %I:%M %p %Z")

throws a 'hexadecimal digit expected' error on JRuby. I don't have an MRI install to quickly try this. Is this expected to work on JRuby?


Anonymous said...

Thanks for this example, exactly what I was looking for!

Anonymous said...

How about '2008-09-29 16:42:23.234'
The last three digits are milliseconds. Please help as I really have to parse this kind of date-times and I dont want to write some ugly parsing code...!

Yuri Rumega said...

Dear Stephen, it's not a mistake that Time#strftime is a private method.
There is an important issue not mentioned in documentation.
DateTime.to_time returns Time object only if time zone is UTC (otherwise returns Self). So if you want to convert your own time string to Time object,
DateTime.strptime("12/25/2007 01:00 AM EST", "%m/%d/%Y %I:%M %p %Z").utc.to_time
should be used. utc and to_time are defined in 'actionsupport' module.

Carlo said...

tnx, very useful