Google Apps Script ~日付の取得~

Google Apps Script

こんにちは、ばばーるです。

今回はGoogle Apps Scriptで日付を取得する方法をご紹介します。

Class DateField  |  Apps Script  |  Google Developers
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);
}
たぬきさん
たぬきさん

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

GAS
GAS

話してたね。
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さん
何かおかしいです。

GAS
GAS

さん付け。

function myFunction() {
  const today = new Date();
  const year = today.getYear(); //年
  console.log(year);
}
GAS
GAS

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/整数現在時刻の秒を返す

次回は日付の操作をご紹介します。

コメント

  1. […] Google Apps Script ~日付の取得~こんにちは、ばばーるです。今回はGoogle Apps … […]

タイトルとURLをコピーしました