Hagelsnow
Hagelsnow

Reputation: 45

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.

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

Upvotes: 1

Views: 679

Answers (4)

Johnny
Johnny

Reputation: 7349

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.

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

Upvotes: 0

Basil Bourque
Basil Bourque

Reputation: 340300

Duration

Adding to the good Answer by Avinash, let me show the use of Duration to track elapsed time.

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.

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

Generate text representing that elapsed time in standard ISO 8601 format: PnYnMnDTnHnMnS .

String output = Duration.toString() ;

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.

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.

Upvotes: 0

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79620

java.time

The java.util Date-Time API is outdated and error-prone. It is recommended to stop using it completely and switch to the modern Date-Time API*.

You can use Instant#now to get the current instant of time. In order to get it every second, you can use ScheduledExecutorService#scheduleWithFixedDelay e.g.

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:

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. The Z in the output is the timezone designator for a zero-timezone offset. It stands for Zulu and specifies the Etc/UTC timezone (which has the timezone offset of +00:00 hours).

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.


* 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. Android 8.0 Oreo already provides support for java.time.

Upvotes: 4

Ermiya Eskandary
Ermiya Eskandary

Reputation: 23702

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.

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

Upvotes: 0

Related Questions