stevep
stevep

Reputation: 235

How do I convert a Firestore Timestamp to a Dart DateTime

I'm mapping a QuerySnapshot from Firestore to one of my Dart classes. One of the fields returned is stored as a Timestamp in Firestore and I need to map it to a DateTime in my model.

In the code snippet below, it errors out on 'dueDate' since UserTask.dueDate is a DateTime object.

return querySnapshot.documents
    .map((doc) => UserTask(
          doc.data['id'],
          doc.data['dueDate'],
        ))
    .toList();

I know I can do it in 2 steps like this: Timestamp ts = d["date"]; date = ts.toDate(); due to the answer here: How Do I convert Stream<QuerySnapshot> to List<myObject>. But how would I do it in the scenario above?

Upvotes: 2

Views: 2338

Answers (1)

Richard Heap
Richard Heap

Reputation: 51682

You could either:

return querySnapshot.documents
    .map((doc) => UserTask(
          doc.data['id'],
          doc.data['dueDate'].toDate(),
        ))
    .toList();

or

return querySnapshot.documents
    .map((doc) {
        var ts = doc.data['dueDate'];
        var date = ts.toDate();
        return UserTask(
          doc.data['id'],
          date,
        );})
    .toList();

Upvotes: 5

Related Questions