1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【GAS初心者】「今日の一ヶ月前」や「初日/末日」の日付を取得する(GAS)

Last updated at Posted at 2020-07-28

#結論

結論
  var date  = new Date(); //現在日時のDateオブジェクトを作る //Tue Jul 28 21:44:30 GMT+09:00 2020

#各論

##今日の取得方法

今日
  var date  = new Date();  //Tue Jul 28 21:44:30 GMT+09:00 2020

正確には「現在日時のDateオブジェクトを作る」ことを行いました。

これを日本人に見やすくするためには、以下の処理を行います。

##今日の表示方法(YYYY/MM/DD)

結論
Utilities.formatDate(date, 'JST', 'yyyy/MM/dd')
今日(YYYY/MM/DD)
  var date  = new Date();  //Tue Jul 28 21:44:30 GMT+09:00 2020
  Utilities.formatDate(date, 'JST', 'yyyy/MM/dd'); //2020/07/28

Utilities.formatDate(date, 'JST', 'yyyy/MM/dd')

##今日→先日へ変更する

結論
.setMonth(date.getMonth() + (-1 || 0));
一ヶ月前の日付を取得する
  var date  = new Date();  //Tue Jul 28 21:44:30 GMT+09:00 2020
  date.setMonth(date.getMonth() + (-1 || 0));
  Utilities.formatDate(date, 'JST', 'yyyy/MM/dd');  //	2020/06/28  

##年、月、日を抜き出す

結論
.slice("ここから","ここまで")
年、月、日を抜き出す
  //Tue Jul 28 21:44:30 GMT+09:00 2020
  var date  = new Date();  
  //2020/07/28
  Utilities.formatDate(date, 'JST', 'yyyy/MM/dd'); 
  //文字列の最初から4文字目まで切り出す-->2020
  var YYYY = beforemonth.slice(0,4); 
  //文字列の5から7文字目まで切り出す-->07
  var MM = beforemonth.slice(5,7); 
  //文字列の8から10文字目まで切り出す-->28
  var DD = beforemonth.slice(8,10);

##先月の初日/末尾を抜き出す

一ヶ月前の初日/末尾を抜き出す
  var YYYY = 2020
  var MM = 07
  var startDate = new Date(YYYY, MM-1, 1); //初日
  var endDate = new Date(YYYY, MM, 0);//末尾
  //2020/06/01 
  var _startDate = Utilities.formatDate(startDate, 'JST', 'yyyy/MM/dd'); 
  //2020/06/30
  var _endDate = Utilities.formatDate(endDate, 'JST', 'yyyy/MM/dd'); 
1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?