LoginSignup
0
0

More than 1 year has passed since last update.

Moment.jsで現在日付からの年度末日を計算する

Posted at

要件

現在日付の年度末の日付を出力したい。
例えば1月1日なら 同年の3月31日だが、4月1日以降は翌年の3月31日を出力すること。
if文を使わず、なるべくモダンなコードで実装すること。

コード

nendoEnd(){
    // まず現在の年度を取得する
    const y = moment().subtract(3, "months").year();
    // 現在の年度の年に1を足して 3月の31日にする
    // ここで注意が必要なのは、month()で設定できるデータはゼロから始まる数値だということです。
    const now = moment()
      .year(y + 1)
      .month(2)
      .endOf('month');
    return now.format("YYYY-MM-DD");
  }

テスト

2022-03-31 → 2022-03-31
2022-04-01 → 2023-03-31

OK!

参考

現在の年度は、3ヶ月前の日付の年を取得することで得られる。
https://qiita.com/togana/items/d622f2e38c67dddba99d

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