【问题标题】:Give timestamp in milliseconds how do I find out if it is older than 2 days以毫秒为单位给出时间戳我如何确定它是否超过 2 天
【发布时间】:2021-10-10 00:59:17
【问题描述】:

我有一个从中获取的时间戳

System.currentTimeMillis()

问题

  1. 如何确定我的代码中这是否超过 2 天?
  2. 有没有更好的方法在创建过程中分配时间戳而不是使用 system.currentTimeMillis ?
  3. System.currentTimeMillis() 机器是否不可知,它是否提供 UTC 时间? 谢谢!

【问题讨论】:

  • “2 天”对您意味着什么?正好48小时?两个日历日,如果是,我们在哪个时区感知日期?
  • 我想检查时间戳是否早于 2 days/48 hours 。这样我就可以使对象过期
  • 2 天不一定是 48 小时。两天可能是 47、47.5、49 或其他小时数。
  • “机器无关”对您意味着什么?

标签: java timestamp timestamp-with-timezone


【解决方案1】:

tl;博士

Instant                              // Represents a moment as seen in UTC.
    .ofEpochMilli( yourCount )       // Convert a count of milliseconds since 1970-01-01T00:00Z to an `Instant` object.
    .isBefore(                       // Compares one `Instant` object to another.
        Instant                      
        .now()                       // Capture the current moment as seen in UTC (an offset of zero).
        .minus(                      // Instantiate another `Instant` object for another moment, per immutable objects pattern.
            Duration.ofHours( 48 )   // Define a span-of-time, not attached to the timeline, on a scale of hours-minutes-seconds.
        )                            // Returns another `Instant` object.
    )                                // Returns `boolean` primitive.

问题 1

如何确定我的代码中这是否超过 2 天?

将您的System.currentTimeMillis() long 整数解析为Instant。

Instant instant = Instant.ofEpochMilli( 1_628_125_542_977L ) ;

你显然想回到 48 小时。

Duration fortyEightHours = Duration.ofHours( 48 ) ;
Instant ago48Hours = Instant.now().minus( fortyEightHours ) ;

比较。

boolean momentIsMoreThan48HoursAgo = instant.isBefore( ago48Hours ) ;

问题 2

有没有更好的方法在创建期间分配时间戳而不是使用 system.currentTimeMillis ?

是的,更好的方法是Instant。

我建议您使用 Instant 类而不是 System.currentTimeMillis()。根据 Java 实现,您可以期望以毫秒或微秒的分辨率捕获当前时刻。

Instant now = Instant.now() ;
String outputIso8601 = now.toString() ;
long millisSinceEpoch = now.toEpochMilli() ;

除非您非常需要紧凑的数据,否则我建议您使用标准ISO 8601 格式的字符串而不是神秘数字来序列化日期时间值。

目前,格式为:2021-08-04T23:06:06Z,其中T 将年月日与时间分开,Z 表示 +00:00 与 UTC 的偏移量零。

问题 3

System.currentTimeMillis() 不是机器不可知论者,它是否提供 UTC 时间?

我不知道您所说的“机器不可知论”是什么意思。该调用确实会跟踪时间,并且它确实取决于正确设置主机的硬件时钟。

至于 UTC 时间,是的,方法 System.currentTimeMillis() 被记录为返回自 1970 年第一刻的 epoch reference 以来的 milliseconds 的数量(给或取,取决于主机硬件时钟的分辨率) offset-from-UTC 为零时分秒,1970-01-01T00:00Z,同时忽略 leap seconds。

Instant 类的作用相同,但可以用nanoseconds 的更精细粒度而不是毫秒来表示时刻。为了捕捉当前时刻,传统的计算机硬件时钟目前只能精确到毫秒到microseconds,而不是纳秒。


所有这些都已经在 Stack Overflow 上多次介绍过。 Search 了解更多。

【讨论】:

  • 谢谢, System.currentTimeMillis() 和 Instant.now() 有什么区别,这是否也给出了 UTC 时间?如果是这样,它是否也与机器无关?
  • (a) 关于您评论的第一个问题,请参阅我的编辑。 (b) 请定义“机器无关”。
【解决方案2】:

这是一种方法。

long millisecond = System.currentTimeMillis();
Instant fixedTime =
        Instant.ofEpochMilli(millisecond);

在这里你可以看到经过时间的持续时间每 5 秒变化一次

for(int i = 0; i < 4; i++) {
    try {
    Thread.sleep(5000);
    } catch (InterruptedException ie){}
    Duration duration = Duration.of(System.currentTimeMillis()
                    -millisecond, ChronoUnit.MILLIS);
    System.out.println(duration);
}

您还可以通过从前一个毫秒中减去当前毫秒然后进行比较来获得经过的持续时间。我选择了hours但是你可以使用任何两天的单位代表。

Duration duration = Duration.of(System.currentTimeMillis()
             -millisecond, ChronoUnit.MILLIS);

if (duration.toHours() >= 48) {
    System.out.println("Two days have elapsed");
}

 

【讨论】:

    【解决方案3】:

    分区日期时间

    不要只使用来自System.currentTimeMillis() 的long 值作为您的时间戳。使用来自现代 Java 日期和时间 API 的 java.time 中的适当日期时间对象。此外,虽然System.currentTimeMillis() 与机器无关——嗯,取决于机器时钟,但假设该时钟已正确设置,System.currentTimeMillis() 与机器和时区无关。但 2 天 不是。由于夏令时 (DST) 和其他时间异常,一天可能是 23、24 或 25 小时或您所在时区的其他持续时间。

    要处理上述所有问题,请选择您要计算 2 天的时区。时区的选择很重要。然后使用ZonedDateTime。它知道其时区并正确处理夏令时转换等。要获取您的时间戳:

        ZoneId zone = ZoneId.of("America/St_Lucia");
        ZonedDateTime timestamp = ZonedDateTime.now(zone);
    

    检查是否超过 2 天:

        ZonedDateTime twoDaysAgo = ZonedDateTime.now(zone).minusDays(2);
        if (timestamp.isBefore(twoDaysAgo)) {
            System.out.println("Timestamp is older than 2 days");
        } else {
            System.out.println("Timestamp is *not* older than 2 days");
        }
    

    由于在这种情况下时间戳当然是新鲜的,所以我现在运行代码时得到的输出是:

    Timestamp is *not* older than 2 days
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-18
      • 2023-03-11
      • 2020-02-22
      • 2011-08-02
      • 1970-01-01
      • 2015-06-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多