【问题标题】:How i can convert "Timestamp(seconds=1621176915, nanoseconds=276147000)" that is string type to actual timestamp type?我如何将字符串类型的“时间戳(秒=1621176915,纳秒=276147000)”转换为实际的时间戳类型?
【发布时间】:2021-10-30 07:20:07
【问题描述】:

我已从 firebase 获取此时间戳,我想将此字符串时间戳转换为实际数据类型。但它给了我一个解析错误,如下所示。

未处理的异常:类型“String”不是类型转换中“Timestamp”类型的子类型

【问题讨论】:

标签: flutter dart


【解决方案1】:

如果您希望将时间戳转换为日期时间格式,这是您可以做到的一种方法:

DateTime get date {
   if (timestamp != null) {
     return timestamp!.toDate();
  }
  return DateTime.now();      
}

【讨论】:

  • 不,实际上我想将字符串“Timestamp(seconds=1621176915, nanoseconds=276147000)”转换为时间戳对象
  • 知道了。请问您为什么要将其保存为时间戳数据类型而不是日期时间或字符串?
  • flutter中没有时间戳对象。
  • 没有,但在 firebase 包中可用
  • @VikramShetty 如果您知道答案,请在此处发表评论,否则我无法告诉您为什么我使用 Timestamp 而不是 DateTime
【解决方案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);

现在您可以使用 postConverted 获取 Timestamp 类型的变量。 我使用了 substring 和 lastIndexOf 方法,它对我有用。

由于纳秒可以是 8 位而不是像这种情况下的 9,所以我们需要使用 lastIndexOf 方法来获取表示纳秒结束的 ')' 的索引。

【讨论】:

  • 谢谢我已经这样做了。顺便说一句,答案很好。
猜你喜欢
  • 2019-05-28
  • 1970-01-01
  • 2021-01-09
  • 2015-01-28
  • 1970-01-01
  • 1970-01-01
  • 2016-08-01
  • 2016-03-04
  • 1970-01-01
相关资源
最近更新 更多