Fundamentals 19 min read

Java 8 Date and Time API Tutorial with Practical Code Examples

This article introduces Java 8's new date‑time API, explains why it replaces the mutable java.util.Date and non‑thread‑safe SimpleDateFormat, and provides a series of clear code examples demonstrating how to obtain current dates, manipulate specific dates, compare dates, handle time zones, work with periods, and format dates using the modern java.time classes.

Selected Java Interview Questions
Selected Java Interview Questions
Selected Java Interview Questions
Java 8 Date and Time API Tutorial with Practical Code Examples

Introduction

Java 8 adds a brand‑new date‑time API that solves the mutability and thread‑safety problems of java.util.Date and SimpleDateFormat . The new API is based on ISO‑8601, provides immutable classes, and is fully thread‑safe.

Key Classes

Instant – a point on the timeline.

LocalDate – a date without time.

LocalTime – a time without date.

LocalDateTime – a date‑time without zone.

ZonedDateTime – a date‑time with zone.

ZoneId and ZoneOffset – zone information.

YearMonth , MonthDay – month‑year and month‑day combinations.

Period – date‑based amount of time.

ChronoUnit – unit‑based amount of time.

Clock – provides the current instant and time‑zone.

Practical Examples

1. Get the current date

public void getCurrentDate() {
    LocalDate today = LocalDate.now();
    System.out.println("Today's Local date : " + today);
    Date date = new Date();
    System.out.println(date);
}

2. Extract year, month, day

public void getDetailDate() {
    LocalDate today = LocalDate.now();
    int year = today.getYear();
    int month = today.getMonthValue();
    int day = today.getDayOfMonth();
    System.out.printf("Year : %d  Month : %d  Day : %d%n", year, month, day);
}

3. Create a specific date

public void handleSpecialDate() {
    LocalDate dateOfBirth = LocalDate.of(2018, 1, 21);
    System.out.println("The special date is : " + dateOfBirth);
}

4. Compare two dates

public void compareDate() {
    LocalDate today = LocalDate.now();
    LocalDate date1 = LocalDate.of(2018, 1, 21);
    if (date1.equals(today)) {
        System.out.printf("TODAY %s and DATE1 %s are same date%n", today, date1);
    }
}

5. Check recurring events (birthday)

public void cycleDate() {
    LocalDate today = LocalDate.now();
    LocalDate dateOfBirth = LocalDate.of(2018, 1, 21);
    MonthDay birthday = MonthDay.of(dateOfBirth.getMonth(), dateOfBirth.getDayOfMonth());
    MonthDay current = MonthDay.from(today);
    if (current.equals(birthday)) {
        System.out.println("Many Many happy returns of the day !!");
    } else {
        System.out.println("Sorry, today is not your birthday");
    }
}

6. Get the current time

public void getCurrentTime() {
    LocalTime time = LocalTime.now();
    System.out.println("local time now : " + time);
}

7. Add hours to a time

public void plusHours() {
    LocalTime time = LocalTime.now();
    LocalTime newTime = time.plusHours(2);
    System.out.println("Time after 2 hours : " + newTime);
}

8. Calculate a date one week later

public void nextWeek() {
    LocalDate today = LocalDate.now();
    LocalDate nextWeek = today.plus(1, ChronoUnit.WEEKS);
    System.out.println("Today is : " + today);
    System.out.println("Date after 1 week : " + nextWeek);
}

9. Add or subtract years

public void minusDate() {
    LocalDate today = LocalDate.now();
    LocalDate previousYear = today.minus(1, ChronoUnit.YEARS);
    System.out.println("Date before 1 year : " + previousYear);
    LocalDate nextYear = today.plus(1, ChronoUnit.YEARS);
    System.out.println("Date after 1 year : " + nextYear);
}

10. Use Clock for timestamps and zones

public void clock() {
    Clock utcClock = Clock.systemUTC();
    System.out.println("Clock : " + utcClock);
    Clock defaultClock = Clock.systemDefaultZone();
    System.out.println("Clock : " + defaultClock);
}

11. Compare dates with isBefore / isAfter

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

12. Work with time zones

public void getZoneTime() {
    ZoneId america = ZoneId.of("America/New_York");
    LocalDateTime local = LocalDateTime.now();
    ZonedDateTime zoned = ZonedDateTime.of(local, america);
    System.out.println("Date and time in specific zone : " + zoned);
}

13. Handle fixed‑date scenarios with YearMonth

public void checkCardExpiry() {
    YearMonth now = YearMonth.now();
    System.out.printf("Days in month %s : %d%n", now, now.lengthOfMonth());
    YearMonth creditCardExpiry = YearMonth.of(2028, Month.FEBRUARY);
    System.out.printf("Your credit card expires on %s%n", creditCardExpiry);
}

14. Determine leap years

public void isLeapYear() {
    LocalDate today = LocalDate.now();
    if (today.isLeapYear()) {
        System.out.println("This year is Leap year");
    } else {
        System.out.println("2018 is not a Leap year");
    }
}

15. Calculate months between two dates

public void calcDateDays() {
    LocalDate today = LocalDate.now();
    LocalDate java8Release = LocalDate.of(2018, Month.MAY, 14);
    Period period = Period.between(today, java8Release);
    System.out.println("Months left between today and Java 8 release : " + period.getMonths());
}

16. Date‑time with explicit offset

public void ZoneOffset() {
    LocalDateTime datetime = LocalDateTime.of(2018, Month.FEBRUARY, 14, 19, 30);
    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

public void getTimestamp() {
    Instant timestamp = Instant.now();
    System.out.println("What is value of this instant " + timestamp);
}

18. Format and parse dates with predefined formatters

public void formateDate() {
    String str = "20180210";
    LocalDate formatted = LocalDate.parse(str, DateTimeFormatter.BASIC_ISO_DATE);
    System.out.printf("Date generated from String %s is %s%n", str, formatted);
}

Summary

The Java 8 date‑time API provides a comprehensive, immutable, and thread‑safe set of classes for handling dates, times, periods, and zones, replacing the legacy java.util.Date and SimpleDateFormat . By using classes such as LocalDate , LocalTime , ZonedDateTime , and utilities like Clock and DateTimeFormatter , developers can write clear, concise, and reliable date‑time code.

javaAPIDateTimeTutorialJava8CodeExamples
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.