2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Next.js】開発環境と本番環境で時間が違う症状の解決方法について

2
Posted at

はじめに

開発中、開発環境と本番環境で時間設定が変わっていたため、こちらの解決方法について共有させていただきます。

2025-07-19T05:19:51.008Z 例えばこのような時間について開発環境と本番環境で以下のように変わってしまっていました。
開発環境:2025-07-19T14:19:51+09:00
本番環境:2025-07-19T05:27:07+09:00

【修正前のコード】

.ts
  console.log(date); // 2025-07-19T05:19:51.008Z string型
  const d = new Date(date); // 2025-07-19T05:19:51.008Z Date型
  const year = date.getFullYear();
  const month = String(date.getMonth()+1).padStart(2, '0'); 
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
   `${year}-${month}-${day}T${hours}:${minutes}:${seconds}+09:00`;

date.getHours() などはローカル環境での値を返してしまうようです。ですので、ローカルが日本時間でも本番環境がUTC(世界標準時)になっていることでズレが生じてしまっていました。

解決方法

.ts
  const jstTime = date.getTime() + 9 * 60 * 60 * 1000; // +9時間分足す
  const jstDate = new Date(jstTime); // number型のタイムスタンプをDate型へ
  const year = jstDate.getUTCFullYear(); // UTCのまま取得する
  const month = String(jstDate.getUTCMonth()+1).padStart(2, '0');
  const day = String(jstDate.getUTCDate()).padStart(2, '0');
  const hours = String(jstDate.getUTCHours()).padStart(2, '0');
  const minutes = String(jstDate.getUTCMinutes()).padStart(2, '0');
  const seconds = String(jstDate.getUTCSeconds()).padStart(2, '0');
   `${year}-${month}-${day}T${hours}:${minutes}:${seconds}+09:00`;
}

参考

おわりに

どなたかの理解のきっかけになれば幸いです。


JISOUのメンバー募集中!

プログラミングコーチングJISOUでは、新たなメンバーを募集しています。
日本一のアウトプットコミュニティでキャリアアップしませんか?
興味のある方は、ぜひホームページをのぞいてみてください!
▼▼▼

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?