How to Print the Current Time in Human Readable Format in Java?

Posted by Joys of Programming on 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

Reblog this post [with Zemanta]


Tags: , ,

Comments:

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Copyright © 2009-2012 Joys of Programming All rights reserved.
Desk Mess Mirrored v1.8.1 theme from BuyNowShop.com.