flutter Firestore 时间戳 终极解决方案

项目场景:

在日常工作中,我们其实很少遇到,需要解析Google firestore 格式的时间戳的问题,正好我前一段时间遇到了,在此分享一下,我解析 Timestamp(seconds=1556459022, nanosecond=0) 时间戳的方法,然而这种时间格式,并不是我们常用的格林威治时间格式,那么我们该怎么来解析呢?


问题描述

当初面临这个问题的时候,我也在网上查阅了大量的文章,但是都无法解决我的问题,在我们拿到数据数据库的时间之后,其实是一个字符串,那么我们首先得把字符串转换成时间的格式,但是需要我们怎么转换呢?


原因分析:

面对上面抛出的问题,我的个人解决方案是,先把 Timestamp(seconds=1556459022, nanosecond=0) 字符串中的seconds 和 nanosecond 的值给提取出来,然后再把两个值赋值给Timestamp 对象,这样我们就能把字符串格式,转换成Timestamp 时间格式了,然后再调用它的toDate() 方法。


解决方案:

具体的解决方案,我在这里封装了一个方法,当然,你也可以直接拿过去使用。

  static DateTime conversionDate(String timestamp) {
    
    
    final int seconds = int.parse(timestamp.substring(18, 28)); // 1621176915
    final int nanoseconds = int.parse(
        timestamp.substring(42, timestamp.lastIndexOf(')'))); // 276147000
    final Timestamp postConverted = Timestamp(seconds, nanoseconds);

    return postConverted.toDate();
  }

猜你喜欢

转载自blog.csdn.net/u010755471/article/details/127731128