In Java, you can get the current date time via following two classes – Date and Calendar. And, later use SimpleDateFormat class to convert the date into a user friendly format.

1. Date() + SimpleDateFormat()

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date)); //2014/08/06 15:59:48

2. Calender() + SimpleDateFormat()

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime())); //2014/08/06 16:00:22

Review a full example to show you how to use Date() and Calender() classes to get and display the current date time.

GetCurrentDateTime.java
package com.mkyong;
 
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
 
public class GetCurrentDateTime {
  public static void main(String[] args) {
 
	   DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
	   //get current date time with Date()
	   Date date = new Date();
	   System.out.println(dateFormat.format(date));
 
	   //get current date time with Calendar()
	   Calendar cal = Calendar.getInstance();
	   System.out.println(dateFormat.format(cal.getTime()));
 
  }
}

Output

2014/08/06 16:06:54
2014/08/06 16:06:54

References

  1. Date JavaDoc
  2. Calendar JavaDoc
  3. SimpleDateFormat JavaDoc
Tags :
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.

Related Posts

Popular Posts