Getting the current date and time is a common task in programming, and it’s essential for many applications.
Java provides built-in classes for working with dates and times, making it easy to retrieve the current date and time.
To get the current date and time in Java, we can use the java.util.Date class or the java.time.LocalDateTime class, which is available since Java 8.
Here is an example program that demonstrates how to use these classes:
import java.util.Date;
import java.time.LocalDateTime;
public class GetCurrentDateTime {
public static void main(String[] args) {
// Using java.util.Date
Date currentDate = new Date();
System.out.println("Current date and time using java.util.Date: " + currentDate);
// Using java.time.LocalDateTime
LocalDateTime currentDateTime = LocalDateTime.now();
System.out.println("Current date and time using java.time.LocalDateTime: " + currentDateTime);
}
}In the above program, we first create an instance of the java.util.Date class using the no-argument constructor, which initializes the date and time to the current system time.
We then print the date and time using the System.out.println() method.
Next, we create an instance of the java.time.LocalDateTime class using the now() method, which returns the current date and time.
We then print the date and time using the System.out.println() method.
Note that the java.util.Date class is considered legacy, and its methods are deprecated since Java 8.
It’s recommended to use the java.time package for working with dates and times in Java.
In conclusion, getting the current date and time in Java is straightforward using the built-in classes provided by Java.
By using the java.time package, we can work with dates and times in a more flexible and robust manner.




