Java计算从当前时间到事件的时间

Rud*_*y B 5 java

我正在尝试计算足球比赛开始前的时间。

这是我所知道的:

  • 我有活动时间:2016-08-16T19:45:00Z
  • 我知道它的字符串格式是“ yyyy-M-dd'T'h:m:s'Z'
  • 我知道时区是“CET”。

我希望能够以天为单位计算从当前时间到此日期的差异。

这是我尝试过的:

    String gameDate = "2016-03-19T19:45:00'Z'"
    DateFormat apiFormat = new SimpleDateFormat("yyyy-M-dd'T'h:m:s'Z'");
    apiFormat.setTimeZone(TimeZone.getTimeZone("CET"));
    Date dateOfGame = apiFormat.parse(gameDate);

    DateFormat currentDateFormat = new SimpleDateFormat("yyyy-M-dd'T'h:m:s'Z'");
    currentDateFormat.setTimeZone(TimeZone.getTimeZone(userTimezone));
    Date currentDate = apiFormat.parse(currentDateFormat.format(new Date()));

    long lGameDate = dateOfGame.getTime();
    long lcurrDate = currentDate.getTime();
    long difference = lGameDate - lcurrDate;
    Date timeDifference = new Date(difference);

    String daysAway = new SimpleDateFormat("d").format(timeDifference);
    Integer intDaysAway = Integer.parseInt(daysAway);
Run Code Online (Sandbox Code Playgroud)

您可能想知道为什么我不只是获取游戏日期 (8) 并减去当前日期 (19)。在当前日期是 29 日而比赛日期是下个月的 3 日的极端情况下,我不会这样做。

dcs*_*ohl 5

还没有人提供 Java 8java.time答案......

    String eventStr = "2016-08-16T19:45:00Z";
    DateTimeFormatter fmt = DateTimeFormatter.ISO_ZONED_DATE_TIME;
    Instant event = fmt.parse(eventStr, Instant::from);
    Instant now = Instant.now();
    Duration diff = Duration.between(now, event);
    long days = diff.toDays();
    System.out.println(days);
Run Code Online (Sandbox Code Playgroud)


ΦXo*_*a ツ 3

尝试做/使用TimeUnit

例子:

final String gameDate = "2016-03-19T19:45:00Z";
final SimpleDateFormat apiFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
apiFormat.setTimeZone(TimeZone.getTimeZone("CET"));
final Date dateOfGame = apiFormat.parse(gameDate);
final long millis = dateOfGame.getTime() - System.currentTimeMillis();
System.out.println(dateOfGame.getTime() - System.currentTimeMillis());

final String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
                TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
                TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
System.out.println(hms);
Run Code Online (Sandbox Code Playgroud)

这将打印输出:

72:57:34

从现在到比赛日期还有 72 小时 57 分 34 秒