0

I have a Firestore Timestamp type field that I want to bring to my Flutter app, do some calculations, then print it on the screen. Everything is working fine for all other types besides the Timestamp. Here's my code (in a StaetefulWidget):

class _SummaryState extends State<Summary> {
  //Firebase
  var annual = DateTime.parse('2021-01-01');
  int overhaul = 5000;
  final firestoreInstance = FirebaseFirestore.instance;
  void fetchAircraft() {
       firestoreInstance
        .collection("aircraft")
        .doc(aircraftID)
        .get()
        .then((value) {
       setState(() {
         overhaul = value.data()["engine"]["overhaul"];
String conversion = value.data()["lastAnnual"].toString();
print('timestamp: $conversion');
         annual = DateTime.parse(value.data()["lastAnnual"]);
       }
   }

   void initState() {
     super.initState();
     fetchAircraft();
   }
...code continues

Overhaul renders well but for the annual date, I get the error:

I/flutter (23628): timestamp: Timestamp(seconds=1596254400, nanoseconds=0) E/flutter (23628): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: type 'Timestamp' is not a subtype of type 'String'

Any idea how to convert Timestamp from Firestore to Flutter? All I want is to use the date from the timestamp to calculate the time between the last inspection and set the new one.

Alex Souza
  • 27
  • 1
  • 6
  • I found the solution here https://stackoverflow.com/questions/56627888/how-to-print-firestore-timestamp-as-formatted-date-and-time – Alex Souza Feb 11 '21 at 17:14
  • Does this answer your question? [How to print Firestore timestamp as formatted date and time](https://stackoverflow.com/questions/56627888/how-to-print-firestore-timestamp-as-formatted-date-and-time) – JM Gelilio Feb 12 '21 at 03:07

1 Answers1

0

Cloud Firestore stores date and time in a Timestamp. Instead of using toString(), you can convert Timestamp to a DateTime object using Timestamp.toDate(). You can then use the DateTime object to extract it in the format of your specification.

Omatt
  • 8,564
  • 2
  • 42
  • 144