On Aug 15, 2013, at 7:15 PM, Phil <
ph...@edgedesign.us> wrote:
> I'm porting an old rails app to Rails 4 and got stumped tonight on time conversions.
>
> This worked:
>
> Loading development environment (Rails 2.3.18)
> > > Time.now.to_s
> => "08/14/2013 07:09PM"
> > > Time.now.to_s.to_time
> => Wed Aug 14 19:09:00 UTC 2013
>
> Now it doesn't on Rails 4.0:
>
> Loading development environment (Rails 4.0.0)
> irb(main):001:0> Time.now
> => 2013-08-15 00:19:48 -0500
> irb(main):002:0> Time.now.to_s
> => "08/15/2013 12:19AM"
> irb(main):003:0> Time.now.to_s.to_time
> ArgumentError: argument out of range
> from /usr/local/lib/ruby/gems/2.0.0/gems/activesupport-4.0.0/lib/active_support/core_ext/string/conversions.rb:23:in `initialize'
> from /usr/local/lib/ruby/gems/2.0.0/gems/activesupport-4.0.0/lib/active_support/core_ext/string/conversions.rb:23:in `new'
>
> If I remove this from my initializer:
>
> Time::DATE_FORMATS.merge!(:default => '%m/%d/%Y %I:%M%p')
>
> It works again in 4.0, but the output format is wrong. I don't want my users reading that time format:
>
> Loading development environment (Rails 4.0.0)
> irb(main):001:0> Time.now.to_s
> => "2013-08-15 00:32:07 -0500"
> irb(main):002:0> Time.now.to_s.to_time
> => 2013-08-15 00:32:15 -0500
>
> If it were a simple single string I was parsing, I could do a custom one off parse and be done with it, but this is site wide. Passing entire hashes to models is causing this error to manifest its self.
>
> Any ideas to get Rails 4.0 to not just produce a custom Time string but parse the same way as well? Seems like it should be simple, but perhaps it's just getting late here. ;')
>
> Thanks!
This isn't a Rails problem, it's something that happens in Ruby. I think it's a bug:
$ irb -r date
irb(main):001:0> format = "%m/%d/%Y"
=> "%m/%d/%Y"
irb(main):002:0> Date.parse(Date.today.strftime(format),format)
ArgumentError: invalid date
from (irb):2:in `parse'
from (irb):2
from /Users/tamara/.rubies/ruby-2.0.0-p427/bin/irb:12:in `<main>'
irb(main):003:0> Date.today.strftime(format)
=> "08/18/2013"
irb(main):004:0> Date.parse(Date.today.to_s)
=> #<Date: 2013-08-18 ((2456523j,0s,0n),+0s,2299161j)>
$ ruby -v
ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-darwin12.4.0]
I don't have anything older to check this on, however, reading the system documentation for strptime(), it seems to state that formats should be compatible with strftime().
A quick test in C[1] shows that the format from strftime to strptime is compatible. So sounds like a ruby bug…
—
[1]
https://gist.github.com/tamouse/6263292