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 it as it is.
This time, I would like to be able to retrieve it with a notation such as
First, let's extract the
created_at of the data
@ post in the
posts table as it is.
<p>Event: <%= @post.event %></p> <p>place: <%= @post.place %></p> <p>Creation date and time: <%= @post.created_at %></p>
|Tokyo||Fireworks display||2020-07-21 00:05:50 UTC|
You can see that it is very different from the target
2020/7/21 9:05:50 notation.
Specifically, the following three points are different.
/is replaced with
I would like to correct it in order.
Since programming is used all over the world, it will be output in
World Standard Time as it is.
Therefore, let's change it to
class Application < Rails::Application # *****Add the following line***** config.time_zone = "Asia/Tokyo" end
By inserting this one line, I was able to change
World Standard Time to
Japan Time as shown below.
|Tokyo||Fireworks display||2020-07-21 09:05:50 ＋0900|
There is a
+0900, which means that the time difference between Japan time and World Standard Time is +9 hours.
It's Japan time, but it's hard to understand if the format is
2020-07-21 09:05:50 + 0900. Let's change it.
First, install the gem for multilingual support and set it to Japanese.
#For Rails6 gem 'rails-i18n', '~> 6.0' #For Rails5 gem 'rails-i18n', '~> 5.1'
class Application < Rails::Application #Abbreviation config.time_zone = "Asia/Tokyo" # *****Add the following line***** config.i18n.default_locale = :ja end
Then use the
l method provided by
<p>Event: <%= @post.event %></p> <p>place: <%= @post.place %></p> <!-- *****add l***** --> <p>Creation date and time: <%= l @post.created_at %></p>
In addition, 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 you don't need
seconds, you can omit
default: "%Y/%m/%d %H:%M"
|Tokyo||Fireworks display||2020/07/21 09:05|
|% m||Month (MONTH)|
|% M||Minutes (MINUTE)|
|% S||seconds (SECOND)|
[Reference page] Ruby 2.7.0 Reference Manual (strftime)
For example, it is unnatural for
July to be written as
07, so let's remove
ja: time: formats: # ***** %Behind-Add***** default: "%Y/%-m/%-d %-H:%M:%S"
|Tokyo||Fireworks display||2020/7/21 9:05:50|
-, we were able to eliminate
0 padding as described above.