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
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
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.
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();
}
(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