Google Apps Scriptでnew Date()だけでは日本の日時は取得不可

new Date()で日本の日時が取得できない

Google Apps Script (GAS)でnew Date()を使用して現在の日時を取得したいことがあるが、GASでnew Date()を実行すると日本時間ではなくEastern Standard Timeで取得してしまう。

この現象はOSやブラウザの言語設定が日本語でも発生する。

function myFunction() {
  console.log(new Date())
  // 日本時間 20:20:17に実行した場合
  // Tue Dec 28 2021 06:20:17 GMT-0500 (Eastern Standard Time)
}

また、この現象はGoogleスプレッドシートのセルに2021/12/28のように日付を入れたものをgetValue()で取得した際も発生してしまう。

日付の場合は「2021/12/28」を取得すると前述のように-14時間となり前日の日付になってしまうので非常に問題がある。

function myFunction() {
  const ss = SpreadsheetApp.getActiveSpreadsheet()
  const sheet = ss.getSheetByName('シート1')

  // セルA2に「2021/12/28」を入れた例
  const date = sheet.getRange('A2').getValue()
  console.log(date)
  // Mon Dec 27 2021 10:00:00 GMT-0500 (Eastern Standard Time)
}

日本時間を取得できないシート例

timeZoneをAsia/Tokyoに変更

前述の問題はappscript.jsonのtimeZoneをAsia/Tokyoに変更すれば修正される。

手順は以下の通り。

  1. プロジェクトの設定ページを開く
  2. 「appsscript.json」マニフェスト ファイルをエディタで表示するを有効にする
  3. エディタに「appsscript.json」が追加されているのでtimeZoneを「Asia/Tokyo」に書き換えて保存する

以上の修正が完了すればnew Date()などを実行しても日本の日時で取得できるようになります。

function myFunction() {
  console.log(new Date())
  // 日本時間 21:00:00に実行した場合
  // Tue Dec 28 2021 21:00:00 GMT+0900 (Japan Standard Time)

  const ss = SpreadsheetApp.getActiveSpreadsheet()
  const sheet = ss.getSheetByName('シート1')

  // セルA2に「2021/12/28」を入れた例
  const date = sheet.getRange('A2').getValue()
  console.log(date)
  // Tue Dec 28 2021 00:00:00 GMT+0900 (Japan Standard Time)
}