🔥
【Firestore】Firestore から取得した Timestamp を DateTime に変換する
Firestore
のセットアップ
pubspec.yaml
dependencies:
flutter:
sdk: flutter
# Add
firebase_core: ^1.1.1
# Add
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
への変換
実装例
import 'package:cloud_firestore/cloud_firestore.dart';
class ApiDataSource {
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
Future<DateTime> fetch() async {
final document = await _firestore
.collection('collectionId')
.doc('documentId')
.get()
.catchError((e) => print(e));
final timestamp = document['createdAt'];
DateTime createdAt = DateTime.now();
if (timestamp is Timestamp) {
createdAt = timestamp.toDate();
}
return createdAt;
}
}
Discussion