[Ruby] How to set display time to Japan time with Rails

1 minute read

Thing you want to do

I want to change the posting time from international standard time to Japan time

Before change (GMT standard time)▼ Screenshot from Gyazo After change (Japan time)▼ Screenshot from Gyazo

Setting method

  • Added config.time_zone ='Tokyo' in config/application.rb


# ↑ The code before this is omitted
module App
  class Application <Rails::Application
    config.time_zone ='Tokyo'
  • If the server is up, shut it out and restart it
    *If docker is running, restart the container as follows (execute the following command in the terminal)
    docker-compose stop
    docker-compose up -d

This is displayed in Japan time, but the format needs to be changed separately

  • Use the strftime method to assign a method to the place where you want to change the display format


# Below is a sample
<td><%= @tweet.created_at.strftime('%Y year %m month %d day %H hour %M minute') %></td>

How to define a conversion method

What to do: Define format conversion in Initialize

  • Create a file called time_formats.rb under config/initializers
  • `Time::DATE_FORMATS[:datetime_jp] =’%Y year %m month %d day %H hour %M minute’


Time::DATE_FORMATS[:datetime_jp] ='%Y year %m month %d day %H hour %M minute'
  • [:Datetime_jp] can be named arbitrarily
  • Describe the format you want to convert in’%Y year %m month %d day %H hour %M minute’.

  • Use .to_s(:datetime_jp]) at the place you want to use (in the view file)


# Below is a sample
<td><%= @tweet.created_at.to_s(:datetime_jp) %></td>