Java Program To Get Current Date and Time
Chapter:
Interview Programs
Last Updated:
14-07-2016 08:16:46 UTC
Program:
/* ............... START ............... */
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class JavaCurrentDateAndTime {
public static void main( String[] args ) {
//Approach 1 to get date and time
Date date1 = new Date();
System.out.println(date1);
//Approach 2 to get date and time
Calendar calendar = Calendar.getInstance();
Date date2 = calendar.getTime();
System.out.println(date2);
//Displaying the date and time - dd/MM/yyyy
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
String dateFormatted = dateFormat.format(date1);
System.out.println(dateFormatted);
//Displaying the date and time - E, dd MMM yyyy HH:mm:ss Z
dateFormat = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z");
dateFormatted = dateFormat.format(date1);
System.out.println(dateFormatted);
//Displaying the date and time - dd-MM-yyy
dateFormat = new SimpleDateFormat("dd-MM-yyyy");
dateFormatted = dateFormat.format(date1);
System.out.println(dateFormatted);
}
}
/* ............... END ............... */
Output
Sat Apr 09 07:52:51 GST 2016
Sat Apr 09 07:52:51 GST 2016
09/04/2016
Sat, 09 Apr 2016 07:52:51 +0400
09-04-2016
Notes:
-
Java provides the Date class available in java.util package, this class encapsulates the current date and time.
- Using SimpleDateFormat and Date/Calendar class, you can easily get current date and time in Java.
Tags
Current Date and Time, Java