【问题标题】:How to get number of days ago from a epoch time from current day? [duplicate]如何从当天的纪元时间获取天数? [复制]
【发布时间】:2021-08-10 15:03:03
【问题描述】:

我有一个纪元时间在字符串中的场景。我需要将其转换为当前时间的天数。

例如:

String epoch = "1600852773514";
Date expiry = new Date(Long.parseLong(epoch));

Expiry 给了我 Wed Sep 23 14:49:33 IST 2020 。但我想得到从今天到时间 'epoch' 的天数。就像纪元是从今天算起的 240 天前。

If expiry > 30 days
pass
else
fail  

【问题讨论】:

  • 你试过什么?它在哪里失败?发布您的代码
  • 我建议你不要使用Date。该课程设计不良且早已过时。而是使用InstantLocalDate 和/或来自java.time, the modern Java date and time API 的其他类。
  • 如果到期时间是 IST 2020 年 9 月 23 日星期三 14:49:33 并且当前时间是 9 月 24 日 13:02,您是否要计算一天(因为日期不同),或者你想在今天 14:49:33 之后才算 1 天吗?
  • 作为一种可能更简单的替代方法,在到期日期和时间上添加 30 天(例如使用 ZonedDateTime.plusDays())并将结果与​​当前时刻进行比较。

标签: java date time format epoch


【解决方案1】:

你可以这样做:

Date expiry = /* ... */;
Date now = new Date();

long days = (now.getTime() - expiry.getTime()) / 86_400_000;

if (days > 30) /* ... */

所以我们以毫秒为单位取时间差:

long diff = (now.getTime() - expiry.getTime());

如果我们除以 86.000.000(这是一天有多少毫秒),我们得到过去的天数。

【讨论】:

  • 谢谢,成功了
  • 这是不正确的。虽然大多数日子有 86 400 000 毫秒长,但并非所有日子都是如此。
【解决方案2】:

作为替代方案,您可以使用 java.time(从 Java 8 开始)并计算两个日期之间的天数:

public static void main(String[] args) {
    // example String
    String epoch = "1618991673000";
    // parse it to a long
    long epochMillis = Long.parseLong(epoch);
    // then create an Instant from that long value
    Instant instant = Instant.ofEpochMilli(epochMillis);
    // and convert it to an OffsetDateTime at UTC (+00:00)
    OffsetDateTime odt = OffsetDateTime.ofInstant(instant, ZoneOffset.UTC);
    // get today's date (only, no time of day considered)
    LocalDate today = LocalDate.now();
    // and extract the date of the OffsetDateTime
    LocalDate then = odt.toLocalDate();
    // count the days between the two dates
    long daysGone = ChronoUnit.DAYS.between(then, today);
    // and print the result...
    System.out.println("Days between " + then
                        + " and today (" + today + "): " + daysGone);
}

此输出(今天,2021 年 5 月 21 日):

Days between 2021-04-21 and today (2021-05-21): 30

之后,您可以轻松检查天数是大于还是小于您的场景中允许的天数。

【讨论】:

    【解决方案3】:

    转换为实例并使用 Duration 类:

    String  epoch = "1600852773514";
    Instant start = Instant.ofEpochMilli(Long.parseLong(epoch));
    Instant now   = Instant.now();
    Long    diff  = Duration.between(start,now).toDays();
    
    System.out.println(diff);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-25
      • 2018-11-24
      • 2012-05-03
      • 2016-03-23
      • 2012-03-12
      • 1970-01-01
      • 2023-03-10
      相关资源
      最近更新 更多