To get the current date and time in Java, use the LocalDateTime
and DateTimeFormatter
classes from the java.time
package:
java
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main {public static void main(String[] args) {
LocalDateTime current = LocalDateTime.now();
DateTimeFormatter format = DateTimeFormatter.ofPattern(“yyyy-MM-dd HH:mm:ss”);
String formattedDate = current.format(format);
System.out.println(“Current Date and Time: “ + formattedDate);
}
}
This outputs the current date and time in the desired format.
This code runs successfully if executed in a Java environment with version 8 or later, as the java.time package was introduced in Java 8.
When you run it, it will print the current date and time in the format yyyy-MM-dd HH:mm:ss.
Make sure your system’s clock and timezone are correctly set for accurate results.