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】FirestoreのTimestampをよくある時間表記にフォーマットする

0
Posted at

依存関係

# pubspec.yaml
dependencies:
  intl: ^0.18.0

起動時にロケールを初期化

日本語の曜日表示には initializeDateFormatting が必要です。

// main.dart
import 'package:intl/date_symbol_data_local.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await initializeDateFormatting('ja'); 
  runApp(const MyApp());
}

Firestore → DateTime に変換

factory ShoppingItem.fromFirestore(
  QueryDocumentSnapshot<Map<String, dynamic>> doc,
) {
  final data = doc.data();
  return ShoppingItem(
    id: doc.id,
    name: data['name'] ?? '',
    lastUpdatedAt: (data['lastBoughtAt'] as Timestamp?)?.toDate(),
    // Timestamp → DateTime に変換
  );
}

表示用フォーマット

import 'package:intl/intl.dart';

String formatDateTime(DateTime? date) {
  if (date == null) return '';
  return DateFormat('M月d日(E) H時mm分', 'ja').format(date);
}

出力例: 3月15日(土) 14時30分

UI に表示

ListTile(
  title: Text(item.name),
  subtitle: Text(
    '${item.createdBy}${formatDateTime(item.lastUpdatedAt)}',
  ),
)

表示イメージ: 太郎・3月15日(土) 14時30分

  • initializeDateFormatting('ja') を main() で呼ぶ(曜日 (E) に必須)
  • Firestore の Timestamp は .toDate() で DateTime に変換

intl + initializeDateFormatting('ja') + DateFormat の3点セットで、Firestore の日時を自然な日本語表示にできます。

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?