【问题标题】:Android studio firestore timestamp comparing to currentLocalTimeAndroid Studio Firestore 时间戳与 currentLocalTime 的比较
【发布时间】:2021-10-27 23:54:30
【问题描述】:

所以我想要的是获取Firestore时间戳和本地设备currentTime的值,并显示不同:

Timestamp timestamp = (Timestamp) document.getData().get("createdAt");
Long tsLong = System.currentTimeMillis()/1000;
//I need the result value of (tsLong - timestamp seconds) 

但我卡在值计算上,如何将时间戳的毫秒数转换为 Long 类型?

【问题讨论】:

    标签: java android firebase google-cloud-firestore timestamp


    【解决方案1】:

    在 firestore 时间戳中,我们有一个 API getSeconds()。此 API 以秒为单位返回时间(long 数据类型)。

    Timestamp timestamp = (Timestamp) document.getData().get("createdAt");
    Long tsLong = System.currentTimeMillis()/1000;
    long result = tsLong - timestamp.getSeconds();
    

    【讨论】:

      【解决方案2】:

      如果有可用的标准 API 来执行相同的计算,请不要自己执行计算。

      import java.time.Instant;
      import java.util.concurrent.TimeUnit;
      
      public class Main {
          public static void main(String[] args) {
              long seconds = TimeUnit.SECONDS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS);
              System.out.println(seconds);
      
              // Alternatively, using java.time API
              seconds = Instant.now().getEpochSecond();
              System.out.println(seconds);
          }
      }
      

      ONLINE DEMO

      回到你的问题:

      您可以使用DocumentSnapshot#getTimestamp 获取Timestamp,您可以使用Timestamp#getSeconds 从中获取秒数。

      因此,您可以这样做

      long diff = TimeUnit.SECONDS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS) - document.getTimestamp("createdAt").getSeconds();
      

      java.time

      java.util 日期时间 API 及其格式化 API SimpleDateFormat 已过时且容易出错。建议完全停止使用,改用modern Date-Time API*

      使用现代日期时间 API java.time 的解决方案:

      使用Timestamp#todate,可以将Timestamp转换成java.util.Date,再转换成java.time.Instant,然后可以使用java.time.Duration求出秒差,如下图:

      long seconds = Duration.between(Instant.now(), document.getTimestamp("createdAt").toDate().toInstant()).toSeconds();
      

      Trail: Date Time 了解有关现代日期时间 API 的更多信息。


      * 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用 ThreeTen-Backport,它将大部分 java.time 功能向后移植到 Java 6 和 7 . 如果您正在为一个 Android 项目工作并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaringHow to use ThreeTenABP in Android Project

      【讨论】:

        【解决方案3】:

        DocumentSnapshot 类包含一个名为getTimestamp(String field) 的方法。因此,获得差异的更简单方法是:

        Timestamp createdAt = document.getTimestamp("createdAt");
        Long seconds = System.currentTimeMillis()/1000;
        long difference = seconds - createdAt.getSeconds();
        

        【讨论】:

        • 嘿,Neko。您是否也尝试过我上面的解决方案?
        猜你喜欢
        • 1970-01-01
        • 2019-03-05
        • 2019-02-14
        • 2019-08-06
        • 1970-01-01
        • 2012-07-09
        • 2021-03-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多