简体   繁体   English

如何每秒更新一次 Date()?

[英]How to update Date() every second?

I am trying to make a program that updates currentTime every second so that in the console it will go 1s, 2s, 3s, 4s and so on.我正在尝试制作一个每秒更新 currentTime 的程序,以便在控制台中它将 go 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.time java.时间

The java.util Date-Time API is outdated and error-prone. java.util日期时间 API 已过时且容易出错。 It is recommended to stop using it completely and switch to the modern Date-Time API * .建议完全停止使用它并切换到现代日期时间 API *

You can use Instant#now to get the current instant of time.您可以使用Instant#now获取当前时刻。 In order to get it every second, you can use ScheduledExecutorService#scheduleWithFixedDelay eg为了每秒获取它,您可以使用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
            );
    }
}

Output from a sample run:样本运行中的 Output:

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

ONLINE DEMO在线演示

An Instant represents an instantaneous point on the timeline, normally represented in UTC time. Instant代表时间线上的一个瞬时点,通常以UTC时间表示。 The Z in the output is the timezone designator for a zero-timezone offset. output 中的Z是零时区偏移量的时区指示符 It stands for Zulu and specifies the Etc/UTC timezone (which has the timezone offset of +00:00 hours).它代表 Zulu 并指定Etc/UTC时区(时区偏移量为+00:00小时)。

Note: If you want to print just the running second, replace the print statement with the following:注意:如果您只想打印正在运行的秒,请将打印语句替换为以下内容:

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

Learn more about the modern Date-Time API from Trail: Date Time .Trail:Date Time了解有关现代日期时间 API 的更多信息。


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project . *出于任何原因,如果您必须坚持Java 6或Java 7 7,您可以使用Threeten- Backport,以备份java888.TIME功能的大部分功能。级别仍然不符合 Java-8,检查Java 8+ APIs available through desugaringHow to use ThreeTenABP in Android Project Android 8.0 Oreo already provides support for java.time . Android 8.0 Oreo 已经提供了java.time的支持

You are updating currentTime outside of the while loop - you are outputting the date to the console every second but you are not updating the time.您正在 while 循环之外更新currentTime - 您每秒将日期输出到控制台,但您没有更新时间。

Try this:尝试这个:

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++;
        }
    }
}

This will create a thread pool with one thread which will execute the lambda printing the number of seconds since the program started once every second.这将创建一个线程池,其中一个线程将执行 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);
    }
}

Duration

Adding to the good Answer by Avinash , let me show the use of Duration to track elapsed time.添加到Avinash 的好答案,让我展示使用Duration来跟踪经过的时间。

Record a starting moment.记录一个开始的时刻。

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

At any other moment, calculate elapsed time on a scale of hours-minutes-seconds using the java.time.Duration class.在任何其他时刻,使用java.time.Duration class 以小时-分钟-秒为单位计算经过的时间。

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

Generate text representing that elapsed time in standard ISO 8601 format: PnYnMnDTnHnMnS .以标准ISO 8601格式生成表示经过时间的文本: PnYnMnDTnHnMnS

String output = Duration.toString() ;

PT21s PT21s

To generate text in a custom format, write a method that accesses the various parts.要以自定义格式生成文本,请编写一个访问各个部分的方法。 Call toHoursPart , toMinutesPart , etc. Put those parts together in whatever way you desire.调用toHoursParttoMinutesPart等。以您想要的任何方式将这些部分放在一起。

Pulling this all together, in the code of that other Answer, change this line:将所有这些放在一起,在另一个答案的代码中,更改此行:

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

… to this line: ...到这一行:

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

… or call your custom formatting method. …或调用您的自定义格式化方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM