Search code examples
javatimeconsolerefresh

Time refresh in the console


I tried to program date and time so that it corresponds to the current date but could not find a solution in the console, only the date of the last run is displayed. Here is my code:

public class DateDemo {

    public static void main(String args[]) {
        Date dNow = new Date();
        SimpleDateFormat ft = new SimpleDateFormat("E dd.MM.yyyy 'um' HH:mm:ss ");
        System.out.println("Datum: " + ft.format(dNow));
    }
}

Solution

  • Consoles behave differently, so I’m afraid that there isn’t any universal solution.

    I tried this:

        DateTimeFormatter formatter
                = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG)
                        .withLocale(Locale.GERMAN);
        ZoneId timeZoneId = ZoneId.of("Europe/Zurich");
        int totalIterations = Math.toIntExact(TimeUnit.HOURS.toSeconds(2));
        for (int sec = 0; sec < totalIterations; sec++) {
            System.out.print(ZonedDateTime.now(timeZoneId).format(formatter) + '\r');
            TimeUnit.SECONDS.sleep(1);
        }
    

    When I run it inside Eclipse, it prints the lines under each other in the Eclipse console like this:

    16. November 2019 07:37:32 MEZ
    16. November 2019 07:37:33 MEZ
    16. November 2019 07:37:34 MEZ
    16. November 2019 07:37:35 MEZ
    

    Screen shot from Eclipse console

    But when I run it from the Terminal window on my Mac, it stays on the same line and just keeps overwriting it:

    Screen shot from Terminal

    The \rcharacter is a carriage return. In theory it should go back to the beginning of the same line. Maybe the reason why it doesn’t in Eclipse is they thought I wanted to use the console window for debugging and therefore would be better served if I could see all output, so they didn’t want to overwrite any. Just guessing.

    There are more elegant and more accurate ways to make something happen every second. Look into ScheduledExecutorService.scheduleAtFixedRate.

    PS The format differs a bit in the two screen shots, in the Terminal window um (“at”) is included between the date and the time. The difference comes from different Java versions. In Eclipse I used Java 8, in the Terminal window Java 11. The story is in this question: JDK dateformatter parsing DayOfWeek in German locale, java8 vs java9.