Get Current Date and Time in Java

In this post we will see that how to get current date and time in java using the class java.util.Date and java.text.SimpleDateFormat.

Below is the code to get current date and time in java using Date class :-

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

public class CurrentDate {
	
 public static void main(String[] args) {
	
	Date dt = new Date();
		
	SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
	
	String currentdate = sdf.format(dt);
	
	System.out.println(currentdate);
	
	 
   }
}

output:-

02-01-2015 18:27:33

the above program will print the current date and time up to seconds. If you want to print the time up to Millisecond then replace HH:mm:ss with HH:mm:ss.SSS .

We can also get the Current Date and time using the java.util.Calendar Class

Below is the code to get current date and time in java using Calendar class :-

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

public class CurrentDate {
	
 public static void main(String[] args) {
			
	SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss.SSS");
	
	Calendar cal = Calendar.getInstance();
	
	String currentdate = sdf.format(cal.getTime());
	
	System.out.println(currentdate);	
	 
   }
}

output:-

02-01-2015 19:40:25.451

There are different date formats are available for displaying the date in different formats like dd/MM/yyyy, dd-MM-yyyy, MM-dd-yyyy etc. For more information you can go to the SimpleDateFormat class documentation.

Leave a Comment