Backend Development 24 min read

Comprehensive Guide to Java 8 Date and Time API

This article provides a thorough walkthrough of Java 8's date‑time API, covering formatting patterns, obtaining current dates and times, extracting components, creating specific dates, comparing dates, handling periodic events, timezone offsets, timestamps, custom parsing, common pitfalls, and thread‑safety considerations, all illustrated with clear code examples.

Selected Java Interview Questions
Selected Java Interview Questions
Selected Java Interview Questions
Comprehensive Guide to Java 8 Date and Time API

1. Java supports date formatting

Define reusable patterns and formatter instances:

import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;

public static final String DATE_TIME_FORMATTER_PATTERN = "yyyy-MM-dd HH:mm:ss";
public static final String DATE_FORMATTER_PATTERN = "yyyy-MM-dd";
public static final String TIME_FORMATTER_PATTERN = "HH:mm:ss";

public static final SimpleDateFormat S_DATE_TIME_FORMATTER = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static final SimpleDateFormat S_DATE_FORMATTER = new SimpleDateFormat("yyyy-MM-dd");
public static final SimpleDateFormat S_TIME_FORMATTER = new SimpleDateFormat("HH:mm:ss");

public static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
public static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
public static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("HH:mm:ss");

2. Get today’s date

Java 8 uses LocalDate to represent a date without time. It differs from java.util.Date which includes both date and time.

LocalDate now = LocalDate.now();
System.out.println(now); // e.g., 2022-12-25

3. Get year, month, and day

LocalDate provides convenient methods to obtain individual components.

LocalDate now = LocalDate.now();
int year = now.getYear();
int month = now.getMonthValue();
int day = now.getDayOfMonth();
System.out.printf("year = %d, month = %d, day = %d", year, month, day);
// Output: year = 2022, month = 12, day = 25

4. Set a specific date

Use the static factory method LocalDate.of() to create any date.

LocalDate date = LocalDate.of(2022, 12, 24);
System.out.println(date); // 2022-12-24

5. Compare two dates for equality

LocalDate now = LocalDate.now();
LocalDate date = LocalDate.of(2022, 12, 25);
LocalDate dateAgo = LocalDate.of(2022, 12, 24);
if (date.equals(now)) {
    System.out.println("是同一天");
}
if (dateAgo.equals(now)) {
    System.out.println("不是同一天");
}

6. Check periodic events (e.g., credit‑card repayment)

Use MonthDay to represent month‑day without a year.

LocalDate now = LocalDate.now();
MonthDay repaymentDate = MonthDay.of(dateOfBirth.getMonth(), dateOfBirth.getDayOfMonth());
MonthDay currentMonthDay = MonthDay.from(now);
if (currentMonthDay.equals(repaymentDate)) {
    System.out.println("today is repayment day");
} else {
    System.out.println("Sorry, today is not repayment day");
}

7. Get current time

LocalTime localTime = LocalTime.now();
System.out.println(localTime); // e.g., 13:35:56.155

8. Add hours to a time

LocalTime localTime = LocalTime.now();
System.out.println(localTime);
LocalTime localTime1 = localTime.plusHours(2); // add 2 hours
System.out.println(localTime1);

9. Calculate the date one week later

LocalDate now = LocalDate.now();
LocalDate plusDate = now.plus(1, ChronoUnit.WEEKS);
System.out.println(now);
System.out.println(plusDate);

10. Calculate a date one year before or after

LocalDate now = LocalDate.now();
LocalDate minusDate = now.minus(1, ChronoUnit.YEARS);
LocalDate plusDate1 = now.plus(1, ChronoUnit.YEARS);
System.out.println(minusDate);
System.out.println(plusDate1);

11. Use the Java 8 Clock class

Clock clock = Clock.systemUTC();
Clock clock1 = Clock.systemDefaultZone();
System.out.println(clock);
System.out.println(clock1);

12. Compare dates with isBefore and isAfter

LocalDate tomorrow = LocalDate.of(2018, 6, 20);
if (tomorrow.isAfter(now)) {
    System.out.println("Tomorrow comes after today");
}
LocalDate yesterday = now.minus(1, ChronoUnit.DAYS);
if (yesterday.isBefore(now)) {
    System.out.println("Yesterday is day before today");
}

13. Represent fixed dates such as credit‑card expiry

YearMonth currentYearMonth = YearMonth.now();
System.out.printf("Days in month year %s: %d%n", currentYearMonth, currentYearMonth.lengthOfMonth());

YearMonth mortgageDueDate = YearMonth.of(2022, Month.JANUARY);
System.out.printf("Your Mortgage due date on %s %n", mortgageDueDate);

14. Determine leap years

boolean isLeap = LocalDate.now().isLeapYear();
System.out.println(isLeap);

15. Calculate days and months between two dates

LocalDate now = LocalDate.now();
LocalDate date = LocalDate.of(2023, Month.MARCH, 20);
Period period = Period.between(now, date);
System.out.println("离下个时间还有" + period.getMonths() + " 个月");

16. Date‑time with timezone offset

LocalDateTime datetime = LocalDateTime.now();
ZoneOffset offset = ZoneOffset.of("+05:30");
OffsetDateTime date = OffsetDateTime.of(datetime, offset);
System.out.println("Date and Time with timezone offset in Java : " + date);

17. Get the current timestamp

Instant timestamp = Instant.now();
System.out.println(timestamp);

18. Custom parsing with DateTimeFormatter

DateTimeFormatter format = DateTimeFormatter.ofPattern("MMMdd yyyy  hh:mm a");
String landing = arrivalDate.format(format);
System.out.printf("Arriving at :  %s %n", landing);

19. Convert a date to a string

LocalDateTime arrivalDate = LocalDateTime.now();
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String landing = arrivalDate.format(format);
System.out.println(landing);

20. Java 8 Date‑Time API summary

Provides java.time.ZoneId for time‑zone handling.

Core classes: LocalDate , LocalTime , LocalDateTime , Instant , OffsetDateTime , YearMonth , MonthDay , Period , Duration .

All classes are immutable and thread‑safe, unlike the old java.util.Date and SimpleDateFormat .

Main package is java.time with sub‑packages java.time.format (formatting) and java.time.temporal (low‑level operations).

Time‑zone IDs follow the Area/City pattern, e.g., Asia/Tokyo .

OffsetDateTime combines LocalDateTime and ZoneOffset to represent a full timestamp with offset.

DateTimeFormatter is immutable, thread‑safe, and offers many built‑in patterns; it can also parse strings, throwing DateTimeParseException on errors.

21. Common Java 8 date‑time operations

Conversion between String , Date , LocalDateTime , and LocalDate using DateTimeFormatter and Instant is demonstrated, as well as adjusting dates (adding days, weeks, months) and calculating intervals with Duration and Period .

22. Date‑time pitfalls and best practices

Using Calendar.HOUR (12‑hour) instead of Calendar.HOUR_OF_DAY (24‑hour) leads to wrong results.

Pattern YYYY is week‑based; use yyyy for calendar year.

Pattern hh is 12‑hour; use HH for 24‑hour.

Months in Calendar are zero‑based (0‑11); add 1 for human‑readable month.

DD represents day‑of‑year; use dd for day‑of‑month.

SimpleDateFormat expects a Date object, not an integer or raw string.

Locale affects parsing; specify Locale.US when parsing English month/day names.

SimpleDateFormat is not thread‑safe; use local variables, ThreadLocal , or synchronize access.

By following these guidelines and using the modern java.time classes, developers can write clear, reliable, and thread‑safe date‑time code in Java 8 and beyond.

JavaDateTimeJava8LocalTimeLocalDateTimeAPIDateTimeFormatter
Selected Java Interview Questions
Written by

Selected Java Interview Questions

A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.