LoginSignup
0
0

時間帯によって変わる表示

Posted at

解決したいこと

時間帯によってTOPページの挨拶文の表示を変えたい。

②タイムゾーンの設定

config/environments/production.rb

Rails.application.configure do
  # ...

  config.time_zone = 'Tokyo'

  # ...

end

config/environments/production.rbファイルには、本番環境での設定が含まれています。

config.time_zoneの値を 'Tokyo' に設定することで、アプリケーションのタイムゾーンを東京に設定することができます。この設定は、デプロイされた環境(本番環境)でのみ有効になります。

②時間帯を条件分岐

app/views/index.html.erb

<% current_hour = Time.zone.now.hour %>
 <% if (4..9).include?(current_hour) %>
   <h1><%= "おはようございます, #{current_user.name}さん!よくお休みになられましたか?"%</h1>
 <% elsif (9..11).include?(current_hour) %>
   <h1><%= "おはようございます, #{current_user.name}さん!良い1日を!"%></h1>
 <% elsif (12..17).include?(current_hour) %>
   <h1><%= "こんにちは, #{current_user.name}さん!お食事されましたか?"%></h1>
 <% elsif (18..21).include?(current_hour) %>
   <h1><%= "こんばんは, #{current_user.name}さん!今日もお疲れさまでした"%></h1>
 <% else %>
   <h1><%= "#{current_user.name}さん!遅い時間まで本当にお疲れさまでした"%></h1>
 <% end %>

解説:

<% current_hour = Time.zone.now.hour %>

<% current_hour = Time.zone.now.hour %>という行は、現在の時間を取得するためのコードです。

<% current_hour = Time.now.hour %>という書き方もありますが、コードはサーバーの時間を基準にしており、サーバーがアメリカの時間に設定されている場合はアメリカの時間が取得されます。
日本の時間を正しく取得するには、Time.zone.now.hourを使用する必要があります。
これにより、Railsアプリケーションの設定で指定したconfig.time_zoneが適用されます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0