2

I have fetched this timestamp from firebase and I want to convert this string timestamp to the actual datatype. But it gives me a parsing error that states below.

Unhandled Exception: type 'String' is not a subtype of type 'Timestamp' in type cast

Hamza Malik
  • 86
  • 1
  • 7
  • Timestamp is not a string. See "How to read Firestore timestamp in Flutter - Stack Overflow" https://stackoverflow.com/questions/55972765/how-to-read-firestore-timestamp-in-flutter – GrahamD Aug 31 '21 at 17:14
  • when i do this Firestore.instance.collection("yourCollectionName").snapshots(); it return me "Timestamp(seconds=1621176915, nanoseconds=276147000)" . how i can convert this – Hamza Malik Aug 31 '21 at 17:17
  • 1
    https://stackoverflow.com/questions/50632217/dart-flutter-converting-timestamp – stacktrace2234 Aug 31 '21 at 17:56

3 Answers3

2
import 'package:cloud_firestore/cloud_firestore.dart'; // for using Timestamp

final String preConverted = "Timestamp(seconds=1621176915, nanoseconds=276147000)";

final int _seconds =
        int.parse(preConverted.substring(18, 28)); // 1621176915
final int _nanoseconds =
        int.parse(preConverted.substring(42, preConverted.lastIndexOf(')'))); // 276147000
final Timestamp postConverted = Timestamp(_seconds, _nanoseconds);

Now you can get a Timestamp typed variable with postConverted. I used a substring and lastIndexOf method and it worked for me.

Because of the nanoseconds can be 8 digits rather than 9 like this case, we need to use lastIndexOf method to take the index of ')' which represents the end of nanoseconds.

0

If you are looking to convert timestamp to a Datetime format, this is one way you can do it :

DateTime get date {
   if (timestamp != null) {
     return timestamp!.toDate();
  }
  return DateTime.now();      
}
Vikram Shetty
  • 119
  • 1
  • 5
0

(Firebase) Here are the ways you can convert that to traditional date string/object;

let datetime = timestamp.toDate()

Doc: https://firebase.google.com/docs/reference/js/firestore_.timestamp#methods

Akshay K Nair
  • 1,107
  • 16
  • 29