Thursday, January 30, 2025
HomeProgrammingHow to Get Current Date and Time in Java

How to Get Current Date and Time in Java

In Java, you can get the current date and time using the LocalDateTime and ZonedDateTime classes from java.time. Here’s an example:

java
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class CurrentDateTime {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
System.out.println("Current Date and Time: " + now.format(formatter));
}
}

For timezone-specific time, use ZonedDateTime.now(). If using Java 7 or older, use new Date() from java.util.Date

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

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