How can I use US-style dates in Rails using Ruby 1.9?

后端 未结 7 1836
攒了一身酷
攒了一身酷 2021-01-04 09:21

I\'m in the U.S., and we usually format dates as "month/day/year". I\'m trying to make sure that my Rails app, using Ruby 1.9, assumes this format everywhere, and

相关标签:
7条回答
  • 2021-01-04 09:56

    For parsing US-style dates, you could use:

    Date.strptime(date_string, '%m/%d/%Y')
    

    In console:

    > Date.strptime('04/01/2011', '%m/%d/%Y')
     => Fri, 01 Apr 2011 
    > Date.strptime('4/1/2011', '%m/%d/%Y')
     => Fri, 01 Apr 2011 
    
    0 讨论(0)
  • 2021-01-04 09:59

    Gem: ruby-american_date

    This gem was created since I asked this question. I'm now using it and have been pleased.

    https://github.com/jeremyevans/ruby-american_date

    0 讨论(0)
  • 2021-01-04 10:10

    Another option is Chronic - http://chronic.rubyforge.org/

    You just need to set the endian preference to force only MM/DD/YYYY date format:

    Chronic::DEFAULT_OPTIONS[ :endian_precedence ] = [ :middle ]
    

    However the default for Chronic is the out-of-order US date format anyway!

    0 讨论(0)
  • 2021-01-04 10:11

    Date.strptime is probably what you're looking for in ruby 1.9.

    You're probably stuck monkeypatching it onto string.to_date for now, but strptime is the best solution for parsing dates from strings in ruby 1.9.

    Also, the formats are symmetric with strftime as far as I know.

    0 讨论(0)
  • 2021-01-04 10:13

    you can use rails-i18n gem or just copy the en-US.yml and set your default locale "en-US" in config/application.rb

    0 讨论(0)
  • 2021-01-04 10:14

    Instead of using to_s for Date instances, get in the habit of using strftime. It takes a format string that gives you complete control over the date format.

    Edit: strptime gives you full control over the parsing by specifying a format string as well. You can use the same format string in both methods.

    0 讨论(0)
提交回复
热议问题