You can use the table column
created_at to retrieve the date and time when the data was created.
However, it is difficult to use the notation as it is.
This time, I’d like to be able to extract it with a notation such as
Display creation date and time
First, let’s fetch the
created_at of the data
@post in the
posts table as it is.
<p>Event: <%= @post.event %></p> <p>Location: <%= @post.place %></p> <p>Created date: <%= @post.created_at %></p>
|Tokyo||Fireworks display||2020-07-21 00:05:50 UTC|
You can see that it is very different from the goal of
Specifically, the following three points are different.
- It is set to
UTC(Coordinated Universal Time)
/is replaced with
- The notation of
I would like to correct it in order.
1. Change from world standard time to Japan time
Since programming is used all over the world, if it is left as it is, it will be output in
World Standard Time.
Therefore, let’s change to
class Application <Rails::Application # ***** Add the following line ***** config.time_zone = "Asia/Tokyo" end
By including this one line, we could change
Coordinated Universal Time to
Japan time as follows.
|Tokyo||Fireworks display||2020-07-21 09:05:50 ＋0900|
+0900, which means that the time difference between Japan time and world standard time is +9 hours.
2. Change the format
It’s Japan time, but it’s difficult to understand if the format is
2020-07-21 09:05:50 ＋ 0900. Let’s change it.
First, install a gem that supports multiple languages and set it to Japanese.
For Rails6 gem'rails-i18n','~> 6.0' For Rails5 gem'rails-i18n','~> 5.1'
class Application <Rails::Application #Omitted config.time_zone = "Asia/Tokyo" # ***** Add the following line ***** config.i18n.default_locale = :ja end
Next, use the
l method provided by
<p>Event: <%= @post.event %></p> <p>Location: <%= @post.place %></p> <!-- ***** l is added ***** --> <p>Created date: <%= l @post.created_at %></p>
Furthermore, let’s create a file called config/locales/ja.yml and set the format.
ja: time: formats: default: "%Y/%m/%d %H:%M:%S"
As a result, the notation changes as follows, and +0900 also disappears.
|Tokyo||Fireworks display||2020/07/21 09:05:50|
The format can be changed freely, for example, if
second is not needed, it can be supported by omitting
default: "%Y/%m/%d %H:%M"
|Tokyo||Fireworks display||2020/07/21 09:05|
[Reference page] Ruby 2.7.0 Reference Manual (strftime)
3. Eliminate zero (0) padding
For example, it is unnatural that
July is written as
07, so remove
ja: time: formats: #-Add *-after %***** default: "%Y/%-m/%-d %-H:%M:%S"
|Tokyo||Fireworks display||2020/7/21 9:05:50|
-, you can eliminate
0 padding as above.