In Java, handling dates and calendars can be done using different APIs depending on which version of Java you’re working with:
✅ Modern Approach (Java 8 and later)
Java 8 introduced the java.time package (JSR-310), which provides a much better and cleaner API for date and time handling.
Common Classes:
LocalDate
→ Date without time (e.g.,2025-08-18
)LocalTime
→ Time without date (e.g.,10:15:30
)LocalDateTime
→ Date and time without timezoneZonedDateTime
→ Date and time with timezonePeriod
→ Difference in years, months, daysDuration
→ Difference in hours, minutes, secondsDateTimeFormatter
→ Formatting and parsing dates
Example:
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class DateExample {
public static void main(String[] args) {
// Current date
LocalDate today = LocalDate.now();
System.out.println("Today's Date: " + today);
// Current date and time
LocalDateTime now = LocalDateTime.now();
System.out.println("Current DateTime: " + now);
// Specific date
LocalDate birthday = LocalDate.of(1995, 8, 18);
System.out.println("Birthday: " + birthday);
// Formatting date
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm");
System.out.println("Formatted DateTime: " + now.format(formatter));
}
}
⚠️ Legacy Approach (Before Java 8)
Older Java versions used java.util.Date
and java.util.Calendar
, but they are considered outdated and confusing.
Example:
import java.util.Date;
import java.util.Calendar;
public class OldDateExample {
public static void main(String[] args) {
// Current date
Date date = new Date();
System.out.println("Current Date: " + date);
// Using Calendar
Calendar calendar = Calendar.getInstance();
System.out.println("Year: " + calendar.get(Calendar.YEAR));
System.out.println("Month: " + (calendar.get(Calendar.MONTH) + 1)); // 0-based
System.out.println("Day: " + calendar.get(Calendar.DAY_OF_MONTH));
}
}
🔑 Key Takeaway:
- Use
java.time
(Java 8+) for modern and clean date handling. - Use
Calendar
/Date
only if you’re working with legacy code.