When I was looking up to display the operating hours of the store, I found that I could specify the time notation by using something called strftime.
view
<%= @laundry.open_time.strftime('%-H:%M')%> 〜 <%= @laundry.close_time.strftime('%-H:%M')%>
Now you can write `07: 00 ~ 23: 00`
.
However, I was worried that `strftime ('% H:% M')`
was repeated twice, and when I was investigating other methods, I found the l method (El method). Record the process of changing from the above writing style to the writing style with the l method.
1 Set the time zone (It was already set when strftime was used, but I will describe it so that I can look back in the future)
Before using the l method, it is necessary to set the time zone so that it is displayed in Japan time (if it is not set, it will be ```UTC (Coordinated Universal Time) `` `, and Japan There is a difference of 9 hours from the time)
config/application.Describe as follows in rb.
#### **`config/application.rb`**
```ruby
config.time_zone = 'Tokyo'
2 Change the default language to ja, create yml file
Set the language to Japanese by writing the following in the same file as 1.
config/application.rb
config.i18n.default_locale = :ja
Create the file in `config / locales``` with the name ``` ja.yml```. (The file is read by matching the country name (ja in the case of Japan) following
default_locale
with 〇〇 in
`〇〇.yml```) in config / locales)
3 Create a format in `` `ja.yml```
ja.yml
ja:
time:
formats:
default: '%-H:%M'
You can change the time notation to your liking by changing the description after default:
.
4 Display the time set in 3 in the view file This is where the l method comes in. By using the l method, the time is displayed using the format specified in the yml file. To use it, add l to the head.
view
<%= l @laundry.open_time %> 〜 <%= l @laundry.close_time %>
Now you can display your preference in time notation without writing `` `strftime``` directly in the view file.
view (strftime direct writing)
<%= @laundry.open_time.strftime('%-H:%M')%> 〜 <%= @laundry.close_time.strftime('%-H:%M')%>
view (using l method)
<%= l @laundry.open_time %> 〜 <%= l @laundry.close_time %>
Use the l method to change the look to be neat! !! By the way, it is also possible to prepare multiple formats and use them properly (see the reference article below).
https://qiita.com/jnchito/items/831654253fb8a958ec25
Recommended Posts