Monday, 23 July 2012

How To Get Current Date Time in Java

In Java, you can get the current date time via following two classes – Date and Calendar.


The SimpleDateFormat class offers a method,  String format(Date date), which formats the given Date into a date/time string according to the format stored in the given SimpleDateFormat object. 

A pattern of special characters is used to specify the format of the date.For example, dd/mm/yyyy, mm/dd/yyyy, yyyy-mm-dd, and so on.


The complete source code is given below:



import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class GetCurrentDateTime {

 public static void main(String[] args) {

  SimpleDateFormat dateFormat = new SimpleDateFormat(
    "yyyy/MM/dd HH:mm:ss");

  // get current date time with Date()

  Date date = new Date();
  System.out
    .println("Current date with Date :" + dateFormat.format(date));

  // get current date time with Calendar()

  Calendar cal = Calendar.getInstance();
  System.out.println("Current date with Calendar :"
    + dateFormat.format(cal.getTime()));

 }

}
The output is given below


Current date with Date :2012/07/23 13:20:31
Current date with Calendar :2012/07/23 13:20:31


The links that may help you:


How to Format Dates and Times using SimpleDateFormat in Java

No comments:

Post a Comment