Ruby 1.87 VS 1.92 Date.Parse

Ruby 1.87 vs 1.92 Date.parse

Use strptime and give a specific time format.

ruby-1.9.2-p136 :022 > Date.strptime '03/21/2011', '%m/%d/%Y'
=> #<Date: 2011-03-21 (4911283/2,0,2299161)>

See michaelmichael's response for the reason for this difference between Ruby versions.

How do I change the format ActiveRecord expects when parsing dates from a text field in a form?

I initially thought this could be solved through the Rails internationalization features, but it turns out I was wrong.

Ever since Ruby 1.9, the standard format for date parsing is dd/mm/yyyy, so as to better accomodate international users. More details can be found in this SO answer.

That standard is maintained in Rails, as Date.parse is now used to process data from form inputs. Using a before_validation callback won't work because the field is going to be received as nil by the callback method.

Right now there are two gems dealing with this specific issue, namely that date parsing in Rails does not follow the locale settings from I18n.locale. Both seem to work well.

  1. delocalize, by clemens - Seems to have been applied successfully in a decent number or projects and has the highest number of stars at the moment.

  2. i18n_alchemy by carlosantoniodasilva - This one has been released more recently. The author is a Rails core team member, and a very active one at that. Definitely deserves a look.

Rails: Date.parse vs string.to_date

If you check the code here, you'll see that the second way of doing this really just invokes the first method with only a minor check for blank-ness.

def to_date
::Date.parse(self, false) unless blank?
end

Regarding the false argument, consulting the docs here:

If the optional second argument is true and the detected year is in the range “00” to “99”, considers the year a 2-digit form and makes it full.

Which should I always parse date times with? DateTime, Time, Time.zone?

Go with Time.zone.parse if you just want to write into ActiveRecord.

DateTime should be avoided. If you're handling dates, you should use Date.parse instead.

Beyond that, it depends on whether the input comes with timezone information, what the current timezone is set to, and whether you want timezones in your data.

Time.zone.parse will return an ActiveSupport::TimeWithZone, defaulting to UTC.

> Time.zone.parse("12:30")
=> Thu, 10 May 2012 12:30:00 UTC +00:00

Time.parse will return a Time, with a zone if it's specified in the input, or the local TZ.

> Time.parse("12:30")
=> 2012-05-09 12:30:00 -0700

For a more detailed explanation of Ruby time comparisons and precision, read this blog post:

http://blog.solanolabs.com/rails-time-comparisons-devil-details-etc/



Related Topics



Leave a reply



Submit