![見出し画像](https://assets.st-note.com/production/uploads/images/68533140/rectangle_large_type_2_efd4a994b738178dded3b903a1a7ea8c.png?width=1200)
GASで日付・時刻がズレる原因は? タイムゾーンを日本時間にする方法
追記(2022/04/16)
『プロジェクトの設定』画面からタイムゾーンの変更ができるようになりました。また、デフォルトのタイムゾーンは『日本時間』です。
![](https://assets.st-note.com/img/1650082875069-B96OVJPBCN.png?width=1200)
日付・時刻がズレる原因は?
GASでDateオブジェクトから日時を取得すると、デフォルトのタイムゾーン(Eastern Standard Time)が反映されます。
Utilities.formatDateで日本のタイムゾーン(JST、Asia/Tokyo)を指定して出力すると+14時間のズレが発生する。
function myFunction() {
//デフォルトのタイムゾーンの日時
const date = new Date("2021/12/31 00:00:00");
console.log("デフォルト: "+date);
//タイムゾーンを日本時間に指定
const strDate = Utilities.formatDate(new Date("2021/12/31 00:00:00"), "JST", "yyyy/MM/dd HH:mm:ss");
console.log("日本時間: "+strDate);
}
![](https://assets.st-note.com/img/1640147781162-8ruWZUCI6h.png?width=1200)
デフォルトのタイムゾーンを変更する
スクリプトエディタの左側のメニューにある「プロジェクトの設定」をクリックする。
![](https://assets.st-note.com/img/1640499827908-BhzxLgOUIe.png?width=1200)
「appsscript.json」マニフェスト ファイルをエディタで表示するにチェックを付ける。
![](https://assets.st-note.com/img/1640500045696-8eXgseFOHW.png?width=1200)
スクリプトエディタに追加されたappsscript.jsonを開き、timeZoneをAsia/Tokyoに書き換える。
![](https://assets.st-note.com/img/1640500232575-o1I0k9R9b6.png?width=1200)
{
"timeZone": "Asia/Tokyo",
"dependencies": {
},
"exceptionLogging": "STACKDRIVER",
"runtimeVersion": "V8"
}
実行して日本時間が表示されるか確認する。
function myFunction() {
//デフォルトのタイムゾーンの日時
const date = new Date();
console.log("デフォルト: "+date);
}
![](https://assets.st-note.com/img/1640500635630-DEoV6YkNIy.png?width=1200)
デフォルトのタイムゾーンのままだと、日時の比較や演算などで意図しない挙動になります。また、数時間のズレなのでエラーが混在しても気づかない可能性があります。Dateオブジェクトを扱う実装の時は、タイムゾーンの設定に注意しましょう。
GASに関する技術的なご質問、お仕事のご依頼
この記事が気に入ったらサポートをしてみませんか?