This is an interview question that was recently asked to a student of mine in a Java Programming Interview. And I thought of sharing it with all who are following my blogpost.
Let me repeat the question once again.
Question: Write a simple program to display the current time in GMT (Greenwich Mean Time) in the format hour:minute:second, such as 14:24:7.
Have you heard of the UNIX epoch. Wait for a minute. There is a method in the System class named ‘currentTimeMillis( )‘ that returns the current time in milliseconds elapsed since the time 00:00:00 on January 1st 1970 GMT. This time is known as the UNIX epoch.
Using this method, we can obtain the current time in milliseconds and then compute the current second, minute and hour as follows.
public class DisplayCurrentTime
public static void main( String  args )
long milliseconds = System.currentTimeMillis( ); // Will give you UNIX epoch
long seconds = milliseconds / 1000; // Will give you the total seconds
//Remember 1 second = 1000 milliseconds
long currentSecond = seconds % 60; // Will give you the current second
long minutes = seconds / 60; // Will give you the total minutes
//Remember 1 minute = 60 seconds
long currentMinute = minutes % 60; // Will give you the current minute
long hours = minutes / 60; // Will give you total hours
//Remember 1 hour = 60 minutes
long currentHour = hours % 24; // Will give you the current hour.
System.out.println( “The current time is ” + currentHour + “:” + currentMinute + “:” + currentSecond + “GMT” );
About the Author:
Subhash.K.U, Principal Mentor,
Subhash Programming Classes, Bangalore
My name is Subhash.K.U. I work as Principal Mentor at Subhash Programming Classes helping fresh engineering graduates and professionals crack their programming interviews through C, C++, Data Structures, Java and Linux Programming.