How to Print the Current Time in Human Readable Format in Java?
currentTimeMillis and nanoTime give the current System time in milliseconds and nano seconds. But this is not understood by humans, since the value returned by these functions is the amount of time passed since January 1,1970
To be able to display the time in human readable format, we make use of the java.util.Calendar. Calendar.getInstance() gives the current time and day. We make use of this function to display the time in human readable format
import java.util.Calendar;
class PrintTime{
private static void printTime(){
int year = Calendar.getInstance().get(Calendar.YEAR );
int month = Calendar.getInstance().get(Calendar.MONTH ) + 1;
int day = Calendar.getInstance().get(Calendar.DAY_OF_MONTH );
int hour = Calendar.getInstance().get(Calendar.HOUR );
int minutes = Calendar.getInstance().get(Calendar.MINUTE );
int seconds = Calendar.getInstance().get(Calendar.SECOND );
System.out.println("Date: "+ year+"-"+ month+ "-"+ day+" "+hour+":"+minutes+":"+seconds);
}
public static void main(String args[]){
printTime();
}
}
The program gives the following output
Date: 2009-11-30 8:5:37
Note how we are making use of the function get() and the various static constants in java.util.Calendar like YEAR, MONTH, DAY_OF_MONTH
Comments:
![Reblog this post [with Zemanta]](http://img.zemanta.com/reblog_e.png?x-id=54abf508-6546-419d-ba0b-2e696a07edcf)