Transforming Datetime into month, day and year?

后端 未结 7 1964
北恋
北恋 2020-12-13 04:36

I can\'t seem to find this and I feel like it should be easy. In Ruby on Rails, how do I take:

2010-06-14 19:01:00 UTC

and turn it into

相关标签:
7条回答
  • 2020-12-13 05:05

    For future reference: Rails date time formats

    0 讨论(0)
  • 2020-12-13 05:07

    Update that is working in Rails 5 :

    <%= l @user.created_at, format: :short %>
    

    Internationalize :

    <%= I18n.l( @user.created_at, format: :short) %>
    

    You can use :long instead of :short

    0 讨论(0)
  • 2020-12-13 05:10

    I don't know for

    June 14th, 2010
    

    But if you want

    June 14, 2010
    

    Ref how do i get name of the month in ruby on Rails? or this

    Just do

    @date = Time.now
    @date.strftime("%B %d, %Y")
    

    And for suffix use following

    @date.strftime("%B #{@date.day.ordinalize}, %Y") # >>> Gives `June 18th, 2010`
    
    0 讨论(0)
  • 2020-12-13 05:12

    Just the other day there was a similar question. In my answer how do I get name of the month in ruby on Rails? I showed how you can add a custom to_s definition in your config/environment.rb file.

    ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(
     :my_own_long_date_format => "%B %d, %Y")
    

    Now you can call Time.now.to_s(:my_own_long_date_format) from any view to get:

    June 15, 2010
    
    0 讨论(0)
  • 2020-12-13 05:16

    Needs the Time module for Time.parse and ActiveSupport for Integer#ordinalize:

    require 'time'
    require 'active_support'
    
    input = '2010-06-14 19:01:00 UTC'
    t = Time.parse(input)
    date = "%s %s, %d" % [t.strftime("%B"), t.day.ordinalize, t.year]
    # => "June 14th, 2010"
    
    0 讨论(0)
  • 2020-12-13 05:20

    You don't need to save it in a variable.

    Time.now.strftime("%Y-%m-%d")  # 2013-01-08
    
    0 讨论(0)
提交回复
热议问题