LoginSignup
8
11

More than 3 years have passed since last update.

gasで月初日と月末日を取得する

Posted at

gasで、というかjavascriptで月初日と月末日を取得するのにどうしたら良いんだろう?と悩んでいたので備忘録。

月初日

Date関数を呼び出すときの第三引数(日付)に1を入れる事で、当月の1日を取得できる。

  var today = new Date();

  // 月初日取得
  Logger.log(new Date(today.getFullYear(), today.getMonth(), 1));

アウトプット

[19-06-16 12:24:55:673 JST] Sat Jun 01 00:00:00 GMT+09:00 2019

月末日

以下の2点

  • Date関数の第二引数を、+1して翌月にする
  • 第三引数を0にして、1日の前日を取得
    • ここを1にすると、6月なら7/1が取得できるが、その前日の6/30を返してくれる
  var today = new Date();

  // 月末日取得
  Logger.log(new Date(today.getFullYear(), today.getMonth()+1, 0));

アウトプット

[19-06-16 12:24:55:674 JST] Sun Jun 30 00:00:00 GMT+09:00 2019

フォーマットする

これだけだと使えないんですよ。
私は2019年6月1日(土)というフォーマットにしたいんですよね。

これをjsで頑張るとこんな感じになります。

  // 月初日取得
  var firstDate = new Date(today.getFullYear(), today.getMonth(), 1);

  var year = firstDate.getFullYear();
  var month = firstDate.getMonth() + 1;
  var date = firstDate.getDate();
  var day = firstDate.getDay();
  var dayList = ["", "", "", "", "", "", ""];

  Logger.log(year + "" + month  + "" + date + "日(" + dayList[day] + ")");

アウトプット

[19-06-16 12:30:37:663 JST] 2019年6月1日(土)

出来たけど、面倒臭いw

moment.jsという便利なライブラリがあった

gasにはライブラリを使う機能があるので、「リソース」 > 「ライブラリ」で、以下のプロジェクトキーを入門してmoment.jsライブラリを追加します。

MHMchiX6c1bwSqGM1PZiW_PxhMjh3Sh48

  var today = new Date();

  // 月初日取得
  var firstDate = new Moment.moment(new Date(today.getFullYear(), today.getMonth(), 1)).format("YYYY年MM月DD日(dddd)");

  Logger.log(firstDate);

formatを使えばこんな感じで出せます。

アウトプット

[19-06-16 12:37:44:770 JST] 2019年06月01日(Saturday)

日本語で曜日を出力するには結局dayListみたいな配列を作るしかないのかな。。それも面倒だな。。
何か良い方法知ってる人いたら教えてください。

8
11
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
8
11