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

John Winters john at sinodun.org.uk
Tue Jul 26 06:20:15 PDT 2011


On 26/07/11 11:55, Paul Robinson wrote:
> On 26 Jul 2011, at 11:39, John Winters wrote:
[snip]
>> 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.

Thanks - that's what I did to begin with but it kind of worried me.  I 
was sure there must be facilities in existence within Rails to do this, 
and felt I was failing to work out how to do it properly.

I rather expected it to default to American date formats, as so much 
stuff does, and was surprised to find it didn't.  That's what got me 
wondering about how to tell it explicitly what to do.

You make reference to "helpers" - can you provide any pointers to those? 
  I keep find myself going round and round in the documentation in the 
area of Date/Time/DateTime, with one bit referring to another bit, which 
refers you to a third bit and then back to the start, with none of them 
providing the hard information.

Cheers,
John



More information about the Chat mailing list