English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn how to get the current date and time in Java format.
import java.time.LocalDateTime; public class CurrentDateTime {}} public static void main(String[] args) { LocalDateTime current = LocalDateTime.now(); System.out.println("Current date and time: ", + current); } }
When running the program, the output is:
Current date and time: 2019-08-02T11:25:44.973
In the above program, the current date and time are stored in the variable current using the LocalDateTime.now() method
For the default format, you just need to use the toString() method internally to convert it from the LocalDateTime object to a string
import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class CurrentDateTime {}} public static void main(String[] args) { LocalDateTime current = LocalDateTime.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS); String formatted = current.format(formatter); System.out.println("Current date and time: ", + formatted); } }
When running the program, the output is:
Current date and time: 2017-08-02 11:29:57.401
In the above program, we used a DateTimeFormatter object to define the format as Year-Month-Day Hours:Minutes:Seconds.Milliseconds pattern
Then, we use the format() method of LocalDateTime to use the given formatter. This gives us the formatted string output.
import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class CurrentDateTime {}} public static void main(String[] args) { LocalDateTime current = LocalDateTime.now(); DateTimeFormatter formatter = DateTimeFormatter.BASIC_ISO_DATE; String formatted = current.format(formatter); System.out.println("The current date is: "); + formatted); } }
When running the program, the output is:
Current date is: 20170802
In the above program, we used the predefined format constant BASIC_ISO_DATE to get the current ISO date as output.
import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.format.FormatStyle; public class CurrentDateTime {}} public static void main(String[] args) { LocalDateTime current = LocalDateTime.now(); DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM); String formatted = current.format(formatter); System.out.println("The current date is: "); + formatted); } }
When running the program, the output is:
The current date is: Aug 2, 2017 11:44:19 AM
In the above program, we used the localized style Medium to get the current date and time in the given format. There are other styles as well, such as: Full, Long, and Short.