【问题标题】:How to update Date() every second?如何每秒更新 Date()?
【发布时间】:2021-10-03 13:04:59
【问题描述】:

我正在尝试制作一个每秒更新 currentTime 的程序,以便在控制台中它将变为 1s、2s、3s、4s 等等。

public static void main(String[] args) throws InterruptedException{
    OSpanel runner = new OSpanel();
    runner.currentTime();
}

public static void currentTime() throws InterruptedException{
    if(true) {
        Date currentTime = new Date();
        while(true) {
            Thread.sleep(1000);
            System.out.println(currentTime);
            Thread.sleep(1000);
            System.out.println(currentTime);
        }
    }
}

【问题讨论】:

  • 是否要从应用程序开始计算时间...
  • 还是四舍五入到最接近的秒数? Java Date rounding - Stack Overflow
  • 无关,但if(true) 应该做什么?此外,如果您想将 currentTime 函数用作实例方法,则它不应该是静态的

标签: java date


【解决方案1】:

java.time

java.util 日期时间 API 已过时且容易出错。建议彻底停止使用,改用modern Date-Time API*

您可以使用Instant#now 获取当前时刻。为了每秒获取它,您可以使用ScheduledExecutorService#scheduleWithFixedDelay 例如

import java.time.Instant;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Main {
    public static void main(String[] args) {
        Executors.newScheduledThreadPool(1)
            .scheduleWithFixedDelay(
                () -> System.out.println(Instant.now()), 
                0, 
                1,
                TimeUnit.SECONDS
            );
    }
}

样本运行的输出:

2021-10-03T13:53:42.462768Z
2021-10-03T13:53:43.469758Z
2021-10-03T13:53:44.470316Z
...

ONLINE DEMO

Instant 表示时间线上的一个瞬时点,通常以UTC 时间表示。输出中的 Z 是零时区偏移的 timezone designator。它代表 Zulu 并指定 Etc/UTC 时区(其时区偏移量为 +00:00 小时)。

注意:如果您只想打印正在运行的秒,请将 print 语句替换为以下内容:

System.out.println(ZonedDateTime.now(ZoneOffset.UTC).getSecond() + "s")

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。 Android 8.0 Oreo 已经提供了support for java.time

【讨论】:

  • 好答案,像往常一样。我建议添加提及最终关闭执行程序服务的内容。为了平滑地增加单秒,我会安排每半秒或每 700 毫秒左右的任务。例如,按整秒调度可能会看到显示的值从 5 秒滑到 7 秒,而跳过 6 秒。
【解决方案2】:

您在 while 循环之外更新 currentTime - 您每秒将日期输出到控制台,但您没有更新时间。

试试这个:

Main.java

public static void main(String[] args) throws InterruptedException{
    OSpanel runner = new OSpanel();
    runner.currentTime();
}

OSpanel.java

public void currentTime() throws InterruptedException{
        int counter = 1;
        while (true) {
            System.out.println(counter + "s");
            Thread.sleep(1000);
            counter++;
        }
    }
}

【讨论】:

  • 这不会打印“1s,2s,3s”
  • 我不确定 OP 在输出方面真正想要什么。
  • “这样在控制台中它将变为 1s、2s、3s、4s 等等”对我来说似乎很明确
  • 已编辑,我知道这很明确,但 60 秒后会发生什么? OP 需要分钟和小时吗?我可以阅读。
【解决方案3】:

Duration

除了Answer by Avinash 之外,让我展示一下使用Duration 来跟踪经过的时间。

记录一个开始的时刻。

Instant start = Instant.now() ;  // Capture the current moment as seen in UTC.

在任何其他时刻,使用 java.time.Duration 类以小时-分钟-秒为单位计算经过的时间。

Duration d = Duration.between( start , Instant.now() ) ;

以标准ISO 8601 格式生成表示已用时间的文本:PnYnMnDTnHnMnS

String output = Duration.toString() ;

PT21s

要生成自定义格式的文本,请编写一个访问各个部分的方法。致电toHoursParttoMinutesPart 等。以您想要的任何方式将这些部分组合在一起。

将所有这些放在一起,在另一个答案的代码中,更改这一行:

() -> System.out.println( Instant.now() ) ,

…到这一行:

() -> System.out.println( Duration.between( start , Instant.now() ).toString() ) ,

…或调用您的自定义格式化方法。

【讨论】:

    【解决方案4】:

    这将创建一个线程池,其中一个线程将执行 lambda,打印自程序每秒启动以来的秒数。

    import java.util.concurrent.Executors;
    import java.util.concurrent.ScheduledExecutorService;
    import java.util.concurrent.TimeUnit;
    
    public class SOAnswer {
        public static void main(String[] args) {
            ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
            long start = System.currentTimeMillis();
            executorService.scheduleAtFixedRate(() -> System.out.println(String.format("%ds", (System.currentTimeMillis() - start) / 1000)), 0, 1, TimeUnit.SECONDS);
        }
    }
    

    【讨论】:

    • 虽然这可能会回答问题,但最好解释一下原因
    猜你喜欢
    • 1970-01-01
    • 2016-04-23
    • 1970-01-01
    • 2013-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-05
    • 1970-01-01
    相关资源
    最近更新 更多