Low Orbit Flux Logo 2 D

Java How To Get Current Date And Time

There exists a variety of different ways to get the current date and time in Java. We’re going to show you what options are available. There may also exist alternative methods that we don’t cover here.

LocalDateTime and DateTimeFormatter Classes

This example will give you output that looks like this:

2021/04/23 14:35:43

Here is an example snippet:

import java.time.format.DateTimeFormatter;   
import java.time.LocalDateTime;     

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
System.out.println(dtf.format(now));

Date and SimpleDateFormat Classes

This example will give you output that looks like this:

23/04/2021 14:44:36

Here is an example snippet:

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

SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date();
System.out.println(formatter.format(date));

Using java.time

The output from each of the lines in the example snippet will look like this:

2021-04-23
14:47:43.550071868
2021-04-23T14:47:43.550158649
2021-04-23T18:47:43.550249680Z

Here is the example snippet:

System.out.println(java.time.LocalDate.now());
System.out.println(java.time.LocalTime.now());
System.out.println(java.time.LocalDateTime.now());
System.out.println(java.time.Clock.systemUTC().instant());

Using System, java.util.Date, java.sql.Date, and java.util.Calendar

The output from each of the lines in the example snippet will look like this:

Fri Apr 23 15:15:27 EDT 2021
Fri Apr 23 15:15:27 EDT 2021
2021-04-23
Fri Apr 23 15:15:27 EDT 2021

Here is the example snippet:

long millis = System.currentTimeMillis();
java.util.Date d1 = new java.util.Date();
java.util.Date d2 = new java.util.Date(millis);
java.sql.Date d3 = new java.sql.Date(millis);
java.util.Date d4 = java.util.Calendar.getInstance().getTime();

System.out.println(d1);
System.out.println(d2);
System.out.println(d3);
System.out.println(d4);