There are multiple ways to get the current date and time in Java programming language. Here we will discuss two ways using java.util.Date and java.util.Calendar Classes.
Using java.util.Date Class
Simply create a new Date() object to get the current date and time. Use the following Java program, In this program, we also used DateTimeFormatter class to show results in proper formats as required.
Output: 04/06/2019 13:23:36
Using java.util.Calendar Class
Use the function Calendar.getInstance() from Calendar class. This provides options for manipulating the calendar fields, such as getting the date of the next week or next month, etc.
You can also use date time format class as above with the below examples.
Output: Wed Apr 17 11:57:28 IST 2019
Using the Calendar class, you can also find the date and time in the past or future. For example, what will the date after or before 10 days of the current date. Similarly, we can do the same for years, months, hours, minutes and seconds as well. Please find below a sample Java program.
Current Date & Time: Wed Apr 17 12:06:05 IST 2019 Date after 10 days: Sat Apr 27 12:06:05 IST 2019 Date before 10 days: Wed Apr 17 12:06:05 IST 2019 Date after 1 month: Fri May 17 12:06:05 IST 2019 Date after 5 years: Fri May 17 12:06:05 IST 2024