我已经从 firebase 获取了这个时间戳,我想将此字符串时间戳转换为实际的数据类型。但它给了我一个解析错误,如下所示。
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);
现在您可以使用 postConverted 获取时间戳类型变量。 我使用了 substring 和 lastIndexOf 方法,它对我有用。
由于纳秒可以是 8 位数字,而不是像本例中的 9 位数字,因此我们需要使用 lastIndexOf 方法来获取表示纳秒结束的 ')' 索引。
关于flutter - 我如何将字符串类型 "Timestamp(seconds=1621176915, nanoseconds=276147000)"转换为实际时间戳类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69002745/