How to format time and date from db:datetime recor

2020-04-12 10:08发布

问题:

I have a var in my view returning date and time from a datetime database record as UTC format. The output looks like this: 2014-01-21 03:13:59 UTC

How do I format this? Date.parse(var) will give #=> Tue, 21 Jan 2014 in IRB but a type error in RAILS 4 of: "no implicit conversion of ActiveSupport::TimeWithZone into String"

I ultimately would like to display just the date; formatted as: %m/%d/%Y My only option can't be to: to_s and regex this right? Someone please show me the RAILS way.

回答1:

Use Date#strftime:

Date.parse('2014-01-21 03:13:59 UTC').strftime('%m/%d/%Y')
# => "01/21/2014"

If var is TimeWithZone object, just call TimeWithZone#strftime method:

var.strftime('%m/%d/%Y')


回答2:

I would argue that the Rails' way is to name that format in an initializer and to use to_formatted_s (or its to_s alias):

# in config/initializers/date_time_formats.rb
Time::DATE_FORMATS.merge!(
  date_us: '%m/%d/%Y'
)
Date::DATE_FORMATS.merge!(
  date_us: '%m/%d/%Y'
)

To use this format in your view:

<%= @object.date.to_s(format: :date_us) %>

This allows you reuse this named format in your application without rewriting the complex strftime string. You can add several different formats and have one place in your app to change an existing format.

If you are going to localize your application into different languages, you might want to store that formats in your locale yml files. This allows you to use different formats depending on the user's location. Read more about that in the Rails Guide about I18n