[LRUG] How does Rails decide how to parse ambiguous dates?

Jordi Noguera Leon jordinoguera83 at gmail.com
Tue Jul 26 03:59:32 PDT 2011


Why don't you use strptime?

http://www.ruby-doc.org/stdlib/libdoc/date/rdoc/classes/Date.html#M000357


On 26 July 2011 11:55, Paul Robinson <paul at 32moves.com> wrote:

> On 26 Jul 2011, at 11:39, John Winters wrote:
>
> > 1) How exactly does Rails interpret a date string typed into a field?
> What method does it use?
>
>
> I always assumed it simply hands it off to Date.parse, which in turn hands
> off to _parse:
>
> http://ruby-doc.org/stdlib/libdoc/date/rdoc/classes/Date.html#M000458
>
>
> > 2) How does one control this behaviour?
>
>
> There are helpers, but if they are seeming a bit confusing or you need/want
> more control, ideally you want to control the input format better, and you
> should consider cleaning the user input into a coherent date format.
>
> For example, Date.parse is 100% consistent with YYYY-MM-DD, and you could
> therefore write a couple of methods to wrap around your actual_date field
> like this:
>
> def user_date
>  return actual_date.strftime("%d/%m/%Y") if current_user.british?
>  return actual_date.strftime("%m/%d/%Y") if current_user.american?
>  ...
> end
>
> def user_date=(date)
>  actual_date = Date.parse("#{date[6,4]}-#{date[3,2]}-#{date[0,2}") if
> current_user.british?
>  actual_date = Date.parse("#{date[6,4]}-#{date[0,2}-#{date[3,2]}") if
> current_user.american?
>  ...
> end
>
> In your forms, just reference user_date... It's an ugly bodge, but it'll
> work if the existing methods aren't what you're after.
>
> Paul
> _______________________________________________
> Chat mailing list
> Chat at lists.lrug.org
> http://lists.lrug.org/listinfo.cgi/chat-lrug.org
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lrug.org/pipermail/chat-lrug.org/attachments/20110726/c801fb7d/attachment-0003.html>


More information about the Chat mailing list