【问题标题】:I am trying to get the remaining time until the next day on a certain hour [closed]我正在尝试在某个时间获得直到第二天的剩余时间[关闭]
【发布时间】:2020-12-12 14:04:32
【问题描述】:

所以我所拥有的是我想要倒计时的时间的小时分钟和秒的 3 个变量。

我怎样才能让它计入我拥有的这个时间,它将输出 3 个变量,其中包含剩余的小时分钟和秒。 谁能帮帮我?

【问题讨论】:

  • 您能分享一下您现有的实现吗?
  • 我没有。我希望得到有关如何的帮助
  • 这能回答你的问题吗? How to calculate time difference in java?
  • 它在倒计时我希望它倒计时
  • 尝试颠倒参数。

标签: java time minecraft


【解决方案1】:

您可以使用java.time.LocalTime 创建开始和结束时间,并以指定的时间间隔循环它们之间的所有时间,例如以下代码以一秒的间隔从start 循环到end

import java.time.LocalTime;

class Main {
    public static void main(String[] args) throws InterruptedException {
        LocalTime start = LocalTime.of(10, 20, 15);
        LocalTime end = LocalTime.of(10, 15, 20);

        // Count down every second from start until end
        for (LocalTime time = start; time.isAfter(end); time = time.minusSeconds(1)) {
            System.out.println(String.format("%02d:%02d:%02d", time.getHour(), time.getMinute(), time.getSecond()));
            Thread.sleep(1000);
        }
    }
}

输出:

10:20:15
10:20:14
10:20:13
...
...
...

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

【讨论】:

    【解决方案2】:

    java.time

    我强烈建议您使用现代 Java 日期和时间 API java.time 来处理您的时间工作。这应该可以帮助您开始:

        int hour = 14;
        int minute = 23;
        int second = 45;
        
        ZoneId zone = ZoneId.systemDefault();
        ZonedDateTime endTime = LocalDate.now(zone)
                .plusDays(1)
                .atTime(LocalTime.of(hour, minute, second))
                .atZone(zone);
        ZonedDateTime now = ZonedDateTime.now(zone);
        Duration remainingTime = Duration.between(now, endTime);
        
        long hoursRemaining = remainingTime.toHours();
        int minutesRemaining = remainingTime.toMinutesPart();
        int secondsRemaining = remainingTime.toSecondsPart();
        
        System.out.format("Remaining: %d hours %d minutes %d seconds%n",
                hoursRemaining, minutesRemaining, secondsRemaining);
    

    刚才在我的时区运行这个sn-p,输出是:

    剩余时间:15 小时 55 分 27 秒

    链接

    Oracle tutorial: Date Time 解释如何使用 java.time。

    【讨论】:

      猜你喜欢
      • 2018-05-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多