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.

Usage:

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

2 comments:

Binil Thomas 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?

Thanks,
Binil

Anonymous said...

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