LoginSignup
0
0

More than 5 years have passed since last update.

【rails5】今月の、月初と月末の日にちを表示させたい

Last updated at Posted at 2018-12-09

【実現したいこと】

今月の、月初と月末の日にちを表示させたい

【方法】

まずDate.todayで今日の日付を作成する

today = Date.today
> Date.today
=> Sun, 09 Dec 2018 

デフォルトの表示から、strftime("%Y-%m-%d")でフォーマットをmm/ddのように変更する。
()内の間のーハイフンを/スラッシュに変えたり、年Yは省略可能。

コンソールにて動作確認

月初はbeginning_of_monthで出力可
today.beginning_of_month.strftime("%m/%d")
=> "12/01"
月末はend_of_monthで出力可
today.end_of_month.strftime("%m/%d")
=> "12/31"

次にファイルを更新。

controller内
@firstday = Date.today.beginning_of_month.strftime("%m/%d")
@lastday = Date.today.end_of_month.strftime("%m/%d")
view内
初日 <%= @firstday %>
締め <%= @lastday %>

で月初12/1、月末12/31と出力出来ました。

2018-12-09 (2).png

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