Display a running digital clock

Digital-ClockIn this post I would be discussing a method to display a running digital clock on the terminal screen or console. In order to display a running digital clock we will fetch the current system time, display the fetched time and then update it after one second.

To get the current system time we will use the Calendar class of java.util package. Current system time can also be obtained through the Date class methods; but we won’t be using it since the Date class had been deprecated since JDK1.1 (in the year 1997!) becauseĀ  it was not amenable to internationalization. Calendar‘s getInstance method returns a Calendar object whose calendar fields have been initialized with the current date and time. We can create a Calendar reference variable ‘rightnow’ and initialize it as follows:

Calendar rightNow = Calendar.getInstance();

Individual fields of time that is hour, minutes and seconds can then be obtained by using the get() function as follows:

rightNow = Calendar.getInstance( );
hour = rightNow.get( Calendar.HOUR );
minute = rightNow.get( Calendar.MINUTE );
second = rightNow.get( Calendar.SECOND );

Time can be displayed inside an infinite loop so that it is refreshed continuously. But, since there is no platform independent way of clearing the screen or a particular portion of the screen the refreshing part is slightly tricky. The problem can solved easily by using the escape sequence \b, the backspace character. The time is of the form “hh:mm:ss”, which is eight characters in total. If we display eight ‘\b’s after displaying the time, the time gets effectively erased. The new time will then be displayed again as the above code would be inside an infinite loop. In order to avoid flickering we would introduce a slight delay before clearing the displayed time. To introduce a delay of one second we will use the sleep( ) function of the Thread class as follows:

Thread.sleep( 1000 );

The function sleep() causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The sleep() function may throw InterruptedException if any thread has interrupted the current thread and hence the enclosing function must declare “throws InterruptedException”. The complete code is as follows:

import java.util.*;
class DigitalClock{
    public static void main( String []args ) throws InterruptedException{
        Calendar rightNow;
        int hour, minute, second;
        String time = "";
        while(true){
            rightNow = Calendar.getInstance( );
            hour = rightNow.get( Calendar.HOUR );
            minute = rightNow.get( Calendar.MINUTE );
            second = rightNow.get( Calendar.SECOND );
            time = ( hour >= 10 ? hour : "0" + hour ) + ":";
            time += ( minute >= 10 ? minute : "0" + minute ) + ":";
            time += ( second >= 10 ? second : "0" + second );
            System.out.print( time );
            Thread.sleep( 1000 );
            System.out.print( "\b\b\b\b\b\b\b\b" );
        }
    }
}

In the above code the conditional (ternary) operator are used to add a zero in the beginning of the respective time component, if hour, minute or second is in single digit so as to keep the length fixed at eight characters. This is done to make it easy to clear the time at the time of refresh. Note that the above code to display a running digital clock would only give correct output when the code is executed in the terminal window because BlueJ IDE is not capable of properly handle escape sequences like ‘\f’, ‘\n’ etc.

Follow me

Vinay Singh

Computer Teacher at Saint John's Academy
I am a GNU/Linux enthusiast and a computer science teacher by profession based at Allahabad, India. My hobbies include reading (mostly computer related stuff) and photography.
Follow me

Latest posts by Vinay Singh (see all)

One thought on “Display a running digital clock

Leave a Reply