0
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?

【Flutter】OpenWeatherMapのdt(UTCタイムスタンプ)を日本時間に変換する方法

Posted at

OpenWeatherMap APIでは、天気予報データに含まれる時間(dt)はUTC(協定世界時)形式のUNIXタイムスタンプ(秒)です。
Flutterアプリで日本のユーザー向けに日本時間(JST)で表示したい場合、DateTimeクラスを使って変換する必要があります。

この記事では、dtをFlutterでローカル時刻に変換し、画面表示などに活用する方法を紹介します。

1. OpenWeatherMapのdtとdt_txtの違いに注意!

APIレスポンス例(抜粋):

{
  "dt": 1753110000,
  "dt_txt": "2025-07-21 15:00:00"
}
  • dt: UTC基準のUNIXタイムスタンプ(秒)

  • dt_txt: UTC基準の時刻文字列

⚠️注意:「dt_txt: "2025-07-21 15:00:00"」は日本時間の15時ではなく、UTCの15時を意味します。

つまりどうなる?

UTC 2025-07-21 15:00:00 +09:00 = JST 2025-07-22 00:00:00

→ 日本で表示する場合は、「7月22日 0時」とするのが正しい!

2. UTC → 日本時間に変換する方法

Flutterでは以下のように変換できます:

final localDateTime = DateTime.fromMillisecondsSinceEpoch(dt * 1000).toLocal();
  • dt * 1000: 秒 → ミリ秒 に変換(DartのDateTimeはミリ秒単位)

  • .toLocal(): 端末のローカルタイムゾーン(日本ならJST)に自動変換

3. 変換結果をフォーマットして表示する(例:7月22日(月) 00:00)

pubspec.yaml に追加:

dependencies:
  intl: ^0.20.2

表示フォーマットコード例:

import 'package:intl/intl.dart';

String formatToJapaneseTime(int dt) {
  final localDateTime =
      DateTime.fromMillisecondsSinceEpoch(dt * 1000).toLocal();

  final formatter = DateFormat('M月d日(E) HH:mm', 'ja');
  return formatter.format(localDateTime);
}

まとめ

APIの dt_txt は UTC 時間です。日本国内向けのUIにそのまま使うと時刻が9時間ずれます!
天気アプリのUIで正確な時刻を日本時間で表示することは、ユーザーの信頼感にもつながります。

0
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
0
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?