概要
Google Apps Script(GAS)で、「現在日」「月初日」「月末日」など日付を取得するコードのメモです。
現在日の取得
- 現在日を取得する方法
function myFunction() {
// 現在日
let now = new Date();
Logger.log(Utilities.formatDate(now, 'Asia/Tokyo', 'yyyy/MM/dd'));
}
当月の月初日の取得
- 当月の月初日を取得する方法
function myFunction() {
// 現在日
let now = new Date();
// 月初日
let startMonthDate = new Date(now.getFullYear(), now.getMonth(), 1);
Logger.log(Utilities.formatDate(startMonthDate, 'Asia/Tokyo', 'yyyy/MM/dd'));
}
月初日は「1日」なので、日付の3つ目の引数(”日”の部分)は”1″固定になります。
指定した年月の月初日の取得
- 年と月を指定する場合の月初日を取得する方法
function myFunction() {
// 年
let year = 2022;
// 月
let month = 9;
// 月初日
let startMonthDate = new Date(year, month - 1, 1);
Logger.log(Utilities.formatDate(startMonthDate, 'Asia/Tokyo', 'yyyy/MM/dd'));
}
月は0〜11で設定をする必要があるため、日付の2つ目の引数(”月”の部分)は-1する必要があります。
当月の月末日の取得
- 当月の月末日を取得する方法
function myFunction() {
// 現在日
let now = new Date();
// 月末日
let endMonthDate = new Date(now.getFullYear(), now.getMonth() + 1, 0);
Logger.log(Utilities.formatDate(endMonthDate, 'Asia/Tokyo', 'yyyy/MM/dd'));
}
月末日は、日付の2つ目の引数(”月”の部分)は翌月になるように”+1″をして日付の3つ目の引数(”日”の部分)は前日にするため”0″を設定します。
指定した年月の月末日の取得
- 年と月を指定する場合の月末日を取得する方法
function myFunction() {
// 年
let year = 2022;
// 月
let month = 9;
// 月末日
let endMonthDate = new Date(year, month , 0);
Logger.log(Utilities.formatDate(endMonthDate, 'Asia/Tokyo', 'yyyy/MM/dd'));
}
月は0〜11で設定をする必要があるため、日付の2つ目の引数(”月”の部分)は-1する必要があります。