こんにちは、ばばーるです。
今回はGoogle Apps Scriptで日付を取得する方法をご紹介します。

Merhod | 戻り値 | 説明 |
new Date(date) | date/日付 | dateの日時を返す。dateの引数がからの場合は現在時刻を返す |
getFullYear() | Integer/整数 | 日付から西暦を返す |
getYear() | Integer/整数 | 日付から1900年からの経過年数を返す |
getMonth() | Month/月 | 日付から1~12月に対応しした数字の0~11を返す |
getDate() | Integer/整数 | 日付から日を返す |
getDay() | Integer/整数 | 曜日を日~土に対応した数字の0~6を返す |
getHours() | Integer/整数 | 現在時刻の時を返す |
getMinutes() | Integer/整数 | 現在時刻の分を返す |
getSeconds() | Integer/整数 | 現在時刻の秒を返す |
new Date()で現在時刻を取得
まずは以下のスクリプトを書いて実行してみましょう。
function myFunction() {
const today = new Date();
console.log(today);
}

ログより[曜日 月 日 年 HH:MM:SS 標準時]の形式で現在時刻が取得されたのが確認できます。
また、日付を入力することで日付の入力もできます。
function myFunction() {
const date = new Date('2020/12/28 13:00:00');
console.log(date);
}


あ~
ここでもこんな話してたね

話してたね。
newDate()と書かないように気を付けてね。
new Date()だよ。

わかった。
でもなんか、長ったらしくて見づらいな。
もっとこう2020/12/30とかで表示して欲しいな。
年月日と曜日を取得する
年月日と曜日を取得するときはget~を使用しましょう。
function myFunction() {
const today = new Date();
const year = today.getFullYear(); //年
const month = today.getMonth(); //月
const date = today.getDate(); //日
const day = today.getDay(); //曜日
console.log(year, month, date, day);
}
ログ出力すると


おお~すげー。
うまく出力されて…ない。
2020 12 30 Wednesdayじゃないのか!
getMonth()で月を取得すると
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] = [1月, 2月, 3月, 4月, 5月, 6月, 7月, 8月, 9月, 10月, 11月, 12月]で表示されます。そのため、12を表示させるためには+1をする必要があります。
const month = today.getMonth() + 1; //月
getDay()で週を取得すると
[0, 1, 2, 3, 4, 5, 6] = [日, 月, 火, 水, 木, 金, 土]で表示されます。そのため文字列に直すためにはスクリプトで調整する必要があります。
function myFunction() {
const today = new Date();
const day = today.getDay(); //曜日
const week = ['日', '月', '火', '水', '木', '金', '土'];
//<-配列を設定
console.log(week[day]);
}
このスクリプトではweekに[日~土]の配列を設定して、出力時にdayの[0~6]を入力することでweekから文字を選択するようにしています。ログを確認すると水が出力されています。


…GASさん
何かおかしいです。

さん付け。
function myFunction() {
const today = new Date();
const year = today.getYear(); //年
console.log(year);
}


getYear()は1900年から何年経ったかを出力するよ。
今年が2020年だから2020 – 1900 = 120の結果だよ。

getFullYear()とgetYear()があるのかややこしいな。
時間の取得
時分秒も取得できます。
function myFunction() {
const today = new Date();
const hours = today.getHours();
const minutes = today.getMinutes();
const seconds = today.getSeconds();
console.log(hours, minutes, seconds);
}

14時4分11秒が出力されました。
まとめ
今回はGoogle Apps Scriptで日付を取得する方法をご紹介しました。
Merhod | 戻り値 | 説明 |
new Date(date) | date/日付 | dateの日時を返す。dateの引数がからの場合は現在時刻を返す |
getFullYear() | Integer/整数 | 日付から西暦を返す |
getYear() | Integer/整数 | 日付から1900年からの経過年数を返す |
getMonth() | Month/月 | 日付から1~12月に対応しした数字の0~11を返す |
getDate() | Integer/整数 | 日付から日を返す |
getDay() | Integer/整数 | 曜日を日~土に対応した数字の0~6を返す |
getHours() | Integer/整数 | 現在時刻の時を返す |
getMinutes() | Integer/整数 | 現在時刻の分を返す |
getSeconds() | Integer/整数 | 現在時刻の秒を返す |
次回は日付の操作をご紹介します。
コメント
[…] Google Apps Script ~日付の取得~こんにちは、ばばーるです。今回はGoogle Apps … […]