简体   繁体   中英

In ruby on rails, how could I convert a time in ActiveSupport::TimeWithZone to Month, Date, Year?

In ruby on rails, how could I convert a time in ActiveSupport::TimeWithZone to Month, Date, Year. For example, I have following time:

Fri, 08 May 2015 22:54:31 UTC +00:00

What I need is like:

05/08/2014

Use strftime like this:

 > t = Time.now
 #=> 2015-05-11 12:47:32 +0530 
 > t.strftime('%m/%d/%Y')
 #=> "05/11/2015" 
irb(main):010:0> DateTime.parse("Fri, 08 May 2015 22:54:31 UTC +00:00").strftime("%d/%m/%Y")
=> "08/05/2015"

使用to_formatted_s方法的此to_s方法别名。

your_var.to_s('%m/%d/%Y')

Visit Strftime Rails api doc

t = Time.now                        #=> 2007-11-19 08:37:48 -0600
t.strftime("Printed on %m/%d/%Y")   #=> "Printed on 11/19/2007"
t.strftime("at %I:%M%p")            #=> "at 08:37AM"

Althought all questions above work and do the job.I18n has a dedicated API for this.

The rails way is described here http://guides.rubyonrails.org/i18n.html

3.3 Adding Date/Time Formats

<p><%= l Time.now, format: :short %></p>

# en.yml
en:
  time:
    formats:
      short: "%m/%d/%Y"

This helps keeps things clean and out of your views.

Hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM