Sunday, March 20, 2011

How to display current date and time ?

It is simple to get the current date, just create a instance of java.util.Date.
    // get current date and time
    java.util.Date date=new java.util.Date();

    // output with default formatting
    System.out.println(""+date);

Under jdk 1.6, the output is something like :
Mon Mar 21 14:00:59 CST 2011

To print the date in a customized way, create a instance of java.text.SimpleDateFormat.

The following is a full sample.

/******************************************************************************
* File : CurrentDate.java
* Author : http://java.macteki.com
* Description :
*   Read current date time and display it in customized format.
* Tested with : JDK 1.6
******************************************************************************/

public class CurrentDate
{
  public static void main(String[] args) throws Exception
  {
    // get current date and time
    java.util.Date date=new java.util.Date();

    // output with default formatting
    System.out.println(""+date);

    // output with customized formatting
    java.text.SimpleDateFormat dateFormat=
      new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    System.out.println(dateFormat.format(date));

  }
}

The output would be something like :
Mon Mar 21 14:00:59 CST 2011
2011-03-21 14:00:59

To do something more interesting, let's create a 'digital clock'.

/******************************************************************************
* File : SimpleClock.java
* Author : http://java.macteki.com
* Description :
*   Display a digital clock
* Tested with : JDK 1.6
******************************************************************************/

import javax.swing.JLabel;

public class SimpleClock {


  public static void main(String[] args) throws Exception
  {

    // create a image label
    JLabel label=new JLabel("", JLabel.CENTER); 
    label.setPreferredSize(new java.awt.Dimension(300,200));

    // create frame
    javax.swing.JFrame frame=new javax.swing.JFrame();
    frame.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);    

    frame.setTitle("Macteki SimpleClock");
   
    frame.add(label);  // add the imageLabel to the frame
    frame.pack();  // set the window size to the size of the component (imageLabel)
    frame.setVisible(true); 

    while (true)
    {
      Thread.sleep(500);
      java.util.Date date=new java.util.Date();
      label.setText(""+date);
    }
  }
}



Thanks for reading. Comments are welcome.

No comments:

Post a Comment