Java – Current date & time

To get current date and time, it is very important to know the Java version used in application. If JDK version is 8 or later then the recommended way is to use LocalDate and LocalTime classes. For applications on Java 7 or below, use of Date and Calendar classes are the options.

1. Current date and time in Java 8 or later

1.1. Get current date

Use LocalDate to get the current date. It contains on the day, month, and year part. No hour/minute part is associated with this.

LocalDate today = LocalDate.now();
		
System.out.println(today);		//2020-05-04

1.2. Get current time

Use LocalTime to get the current time. It gives the time upto milliseconds precision.

LocalDate today = LocalDate.now();
		
System.out.println(today);		//23:46:10.398

1.3. Get current date AND time

Use LocalTime to get the current time. It gives the time upto milliseconds precision.

LocalDateTime instance = LocalDateTime.now();
		
System.out.println(instance);		//2020-05-04T23:48:12.700

1.4. Display formatted date time string

To default string representations of the above classes are fixed. If you want to display in some custom pattern, use DateTimeFormatter class.

LocalDateTime instance = LocalDateTime.now();

DateTimeFormatter formatter 
	= DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm");

System.out.println(formatter.format(instance));	// 04-05-2020 11:50

2. Current date and time in Java 7 or earlier

2.1. Get current date AND time

Till version 7 or earlier, Java didn’t had separate classes for date and time part. Main classes were java.util.Date
and java.util.Calendar, and both came with date and time part.

Date date = new Date();

Calendar cal = Calendar.getInstance();
		
System.out.println(date);	//Mon May 04 23:53:49 IST 2020

1.2. Display formatted date time string

To display, date time in formatted pattern in Java 7, we should use SimpleDateFormat class.

Date date = new Date();
Calendar cal = Calendar.getInstance();

SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm");  

System.out.println(sdf.format(date));  			//05-05-2020 12:01
System.out.println(sdf.format(cal.getTime()));	//05-05-2020 12:01

Drop me your questions related to getting current date and time in Java.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.