Firestoreから取得したTimestampをDateTimeに変換する

1 min read

Firestoreの初期設定

pubspec.yaml

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2

  # 追加
  firebase_core: ^1.1.1
  cloud_firestore: ^2.1.0

main.dart

import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

TimestampからDateTimeへの変換

Firestoreの構成

collection -> document -> createdAt[Timestamp]

Flutterの実装

import 'package:cloud_firestore/cloud_firestore.dart';

class ApiDataSource {
  final FirebaseFirestore _firestore = FirebaseFirestore.instance;

  Future fetch() async {
    final document = await _firestore
        .collection('collectionId')
        .doc('documentId')
        .get()
        .catchError((e) => print(e));

    var timestamp = document['createdAt'];
    DateTime createdAt;
    if (timestamp is Timestamp) {
      // toDate()でDateTimeに変換
      createdAt = timestamp.toDate();
    } else {
      createdAt = DateTime.now();
    }
    
    ...
  }
}