Monday, January 6, 2025
HomeProgrammingHow to Get Current Date and Time in Java

How to Get Current Date and Time in Java

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);
}
}

See also  Data Structures Tutorial

This outputs the current date and time in the desired format.

Previous article
Next article
RELATED ARTICLES

1 COMMENT

5 1 vote
Article Rating

Leave a Reply

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Bethany Devson

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.

- Advertisment -

Most Popular

Recent Comments

1
0
Would love your thoughts, please comment.x
()
x