Rails db won't save string as date with m / d / y format?

saving a string in my db as a date and getting some weird results

if the date is formatted,

dd / mm / yy it will save

if the date is formatted,

mm / dd / yy he will not be able to safely save

in my console if i go

'20/10/2012'.to_date => Sat, 20 Oct 2012 

works

if i go

 '10/20/2012'.to_date => ArgumentError: invalid date ... 

he is breaking

I used the initializer to set the default date format to% m /% d /% Y, which you can see is exactly reflected in my DATE_FORMATS hash.

 Date::DATE_FORMATS => {:short=>"%e %b", :long=>"%B %e, %Y", :db=>"%Y-%m-%d", :number=>"%Y%m%d", :long_ordinal=>#<Proc: 0x007f8663f1aae0@ /Users/ian/.rvm/gems/ ruby-1.9.3-p0@rails-3.2 /gems/activesupport-3.2.1/lib/active_support/core_ext/date/conversions.rb:12 (lambda)>, :rfc822=>"%e %b %Y", :default=>"%m/%d/%Y"} 

It is unclear what is the cause of this problem, as the situation seems to be configured correctly. How to allow?

Thank you!

+4
source share
2 answers

Try:

 DateTime.strptime('20/10/2012', '%d/%m/%Y') 

Or just use Date if you don't need the associated time:

 Date.strptime('20/10/2012', '%d/%m/%Y') 
+2
source

Use gem american_date

In the gem file gem 'american_date'

Now it will save the date format mm / dd / yyyy.

+2
source

Source: https://habr.com/ru/post/1439657/


All Articles