The Java Date & Time API provides classes to work with dates, times, durations, and time zones.
Date and Calendar, which were confusing and not thread-safe.java.time package was introduced (inspired by Joda-Time library).Date, Calendar) were poorly designed.The new API solved these problems with cleaner, more reliable classes.
1. LocalDate → Represents only a date (no time).import java.time.LocalDate;
public class Example {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
System.out.println("Today's Date: " + today);
}
}
2. LocalTime → Represents only time (no date).import java.time.LocalTime;
LocalTime time = LocalTime.now();
System.out.println("Current Time: " + time); LocalDateTime → Represents date and time together.import java.time.LocalDateTime;
LocalDateTime now = LocalDateTime.now();
System.out.println("Date & Time: " + now); ZonedDateTime → Represents date-time with time zone.import java.time.ZonedDateTime;
ZonedDateTime zone = ZonedDateTime.now();
System.out.println("Zoned Date & Time: " + zone);
Period & Duration → Represent amounts of time.import java.time.*;
LocalDate start = LocalDate.of(2020, 1, 1);
LocalDate end = LocalDate.now();
Period period = Period.between(start, end);
System.out.println("Years passed: " + period.getYears());
DateTimeFormatter → For formatting and parsing.import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm");
System.out.println("Formatted Date: " + now.format(formatter));
Date class).The Java Date & Time API (java.time) is one of the best additions in Java 8. It replaced confusing old APIs with a modern, clean, and powerful approach.
With classes like LocalDate, LocalTime, LocalDateTime, and ZonedDateTime, working with time has never been easier. It’s a must-know for any Java developer building real-world applications.
Latest tech news and coding tips.
1. What Is the Golden Ratio? The Golden Ratio, represented by the Greek letter φ (phi), is…
In CSS, combinators define relationships between selectors. Instead of selecting elements individually, combinators allow you to target elements based…
Below is a comprehensive, beginner-friendly, yet deeply detailed guide to Boolean Algebra, complete with definitions, laws,…
Debugging your own code is hard enough — debugging someone else’s code is a whole…
Git is a free, open-source distributed version control system created by Linus Torvalds.It helps developers: Learn how to…
Bubble Sort is one of the simplest sorting algorithms in computer science. Although it’s not…