Backend Development 23 min read

Java 8 Date and Time API Tutorial with Practical Examples

This article introduces Java 8's new date‑time API, explains its immutable and thread‑safe design, lists the key classes such as Instant, LocalDate, LocalTime, ZonedDateTime, and provides step‑by‑step code examples for obtaining current dates, manipulating specific dates, handling time zones, calculating intervals, and formatting dates.

Architect's Tech Stack
Architect's Tech Stack
Architect's Tech Stack
Java 8 Date and Time API Tutorial with Practical Examples

Java 8 introduced a modern date‑time API that replaces the mutable and non‑thread‑safe java.util.Date and SimpleDateFormat with immutable, thread‑safe classes in the java.time package, following ISO standards and offering clearer concepts like Instant , Duration , LocalDate , LocalTime , ZonedDateTime , and more.

Key Classes

Instant : represents a point in time.

LocalDate : date without time, e.g., birthdays.

LocalTime : time without date.

LocalDateTime : date and time without zone.

ZonedDateTime : full date‑time with zone information.

The API also adds ZoneOffset , ZoneId , and DateTimeFormatter for easier time‑zone handling and formatting.

Practical Examples

1. Get 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 Specific Date

//处理特定日期
public void handleSpecilDate(){
    LocalDate dateOfBirth = LocalDate.of(2018, 01, 21);
    System.out.println("The specil date is : " + dateOfBirth);
}

4. Compare Two Dates

//判断两个日期是否相等
public void compareDate(){
    LocalDate today = LocalDate.now();
    LocalDate date1 = LocalDate.of(2018, 01, 21);
    if(date1.equals(today)){
        System.out.printf("TODAY %s and DATE1 %s are same date %n", today, date1);
    }
}

5. Handle Recurring Events (Birthday)

//处理周期性的日期
public void cycleDate(){
    LocalDate today = LocalDate.now();
    LocalDate dateOfBirth = LocalDate.of(2018, 01, 21);
    MonthDay birthday = MonthDay.of(dateOfBirth.getMonth(), dateOfBirth.getDayOfMonth());
    MonthDay currentMonthDay = MonthDay.from(today);
    if(currentMonthDay.equals(birthday)){
        System.out.println("Many Many happy returns of the day !!");
    } else {
        System.out.println("Sorry, today is not your birthday");
    }
}

6. Get Current Time

//获取当前时间
public void getCurrentTime(){
    LocalTime time = LocalTime.now();
    System.out.println("local time now : " + time);
}

7. Add Hours to Time

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

8. Calculate 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. Calculate One Year Before/After

//计算一年前或一年后的日期
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

//使用Java 8的Clock时钟类
public void clock(){
    Clock clock = Clock.systemUTC();
    System.out.println("Clock : " + clock);
    Clock defaultClock = Clock.systemDefaultZone();
    System.out.println("Clock : " + clock);
}

11. Compare Dates with isBefore / isAfter

//如何用Java判断日期是早于还是晚于另一个日期
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. Time‑Zone Handling

//获取特定时区下面的时间
public void getZoneTime(){
    ZoneId america = ZoneId.of("America/New_York");
    LocalDateTime localtDateAndTime = LocalDateTime.now();
    ZonedDateTime dateAndTimeInNewYork = ZonedDateTime.of(localtDateAndTime, america);
    System.out.println("现在的日期和时间在特定的时区 : " + dateAndTimeInNewYork);
}

13. YearMonth for Fixed Dates (e.g., Credit Card Expiry)

//使用 YearMonth类处理特定的日期
public void checkCardExpiry(){
    YearMonth currentYearMonth = YearMonth.now();
    System.out.printf("Days in month year %s: %d%n", currentYearMonth, currentYearMonth.lengthOfMonth());
    YearMonth creditCardExpiry = YearMonth.of(2028, Month.FEBRUARY);
    System.out.printf("Your credit card expires on %s %n", creditCardExpiry);
}

14. Leap Year Check

//检查闰年
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 Period Between Dates

//计算两个日期之间的天数和月数
public void calcDateDays(){
    LocalDate today = LocalDate.now();
    LocalDate java8Release = LocalDate.of(2018, Month.MAY, 14);
    Period periodToNextJavaRelease = Period.between(today, java8Release);
    System.out.println("Months left between today and Java 8 release : " + periodToNextJavaRelease.getMonths());
}

16. Date‑Time with Zone 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 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 dayAfterTommorrow = "20180210";
    LocalDate formatted = LocalDate.parse(dayAfterTommorrow, DateTimeFormatter.BASIC_ISO_DATE);
    System.out.printf("Date generated from String %s is %s %n", dayAfterTommorrow, formatted);
}

Full Source Code

package com.wq.study.java8.date;

import java.time.Clock;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.MonthDay;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.Period;
import java.time.YearMonth;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Date;

public class DateTest {
    //获取今天的日期
    public void getCurrentDate(){
        LocalDate today = LocalDate.now();
        System.out.println("Today's Local date : " + today);
        Date date = new Date();
        System.out.println(date);
    }
    //获取年、月、日信息
    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 t %n", year, month, day);
    }
    //处理特定日期
    public void handleSpecilDate(){
        LocalDate dateOfBirth = LocalDate.of(2018, 01, 21);
        System.out.println("The specil date is : " + dateOfBirth);
    }
    //判断两个日期是否相等
    public void compareDate(){
        LocalDate today = LocalDate.now();
        LocalDate date1 = LocalDate.of(2018, 01, 21);
        if(date1.equals(today)){
            System.out.printf("TODAY %s and DATE1 %s are same date %n", today, date1);
        }
    }
    //处理周期性的日期
    public void cycleDate(){
        LocalDate today = LocalDate.now();
        LocalDate dateOfBirth = LocalDate.of(2018, 01, 21);
        MonthDay birthday = MonthDay.of(dateOfBirth.getMonth(), dateOfBirth.getDayOfMonth());
        MonthDay currentMonthDay = MonthDay.from(today);
        if(currentMonthDay.equals(birthday)){
            System.out.println("Many Many happy returns of the day !!");
        } else {
            System.out.println("Sorry, today is not your birthday");
        }
    }
    //获取当前时间
    public void getCurrentTime(){
        LocalTime time = LocalTime.now();
        System.out.println("local time now : " + time);
    }
    //增加小时
    public void plusHours(){
        LocalTime time = LocalTime.now();
        LocalTime newTime = time.plusHours(2); // 增加两小时
        System.out.println("Time after 2 hours : " +  newTime);
    }
    //如何计算一周后的日期
    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);
    }
    //计算一年前或一年后的日期
    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);
    }
    public void clock(){
        // 根据系统时间返回当前时间并设置为UTC。
        Clock clock = Clock.systemUTC();
        System.out.println("Clock : " + clock);
        // 根据系统时钟区域返回时间
        Clock defaultClock = Clock.systemDefaultZone();
        System.out.println("Clock : " + clock);
    }
    //如何用Java判断日期是早于还是晚于另一个日期
    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");
        }
    }
    //时区处理
    public void getZoneTime(){
        //设置时区
        ZoneId america = ZoneId.of("America/New_York");
        LocalDateTime localtDateAndTime = LocalDateTime.now();
        ZonedDateTime dateAndTimeInNewYork  = ZonedDateTime.of(localtDateAndTime, america );
        System.out.println("现在的日期和时间在特定的时区 : " + dateAndTimeInNewYork);
    }
    //使用 YearMonth类处理特定的日期
    public void checkCardExpiry(){
        YearMonth currentYearMonth = YearMonth.now();
        System.out.printf("Days in month year %s: %d%n", currentYearMonth, currentYearMonth.lengthOfMonth());
        YearMonth creditCardExpiry = YearMonth.of(2028, Month.FEBRUARY);
        System.out.printf("Your credit card expires on %s %n", creditCardExpiry);
    }
    //检查闰年
    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");
        }
    }
    //计算两个日期之间的天数和月数
    public void calcDateDays(){
        LocalDate today = LocalDate.now();
        LocalDate java8Release = LocalDate.of(2018, Month.MAY, 14);
        Period periodToNextJavaRelease = Period.between(today, java8Release);
        System.out.println("Months left between today and Java 8 release : " + periodToNextJavaRelease.getMonths() );
    }
    // 包含时差信息的日期和时间
    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);
    }
    // 获取时间戳
    public void getTimestamp(){
        Instant timestamp = Instant.now();
        System.out.println("What is value of this instant " + timestamp);
    }
    // 使用预定义的格式化工具去解析或格式化日期
    public void formateDate(){
        String dayAfterTommorrow = "20180210";
        LocalDate formatted = LocalDate.parse(dayAfterTommorrow, DateTimeFormatter.BASIC_ISO_DATE);
        System.out.printf("Date generated from String %s is %s %n", dayAfterTommorrow, formatted);
    }
    public static void main(String[] args) {
        DateTest dt = new DateTest();
        dt.formateDate();
    }
}

Summary of Java 8 Date‑Time API

The new API provides thread‑safe, immutable classes such as LocalDate , LocalTime , and ZonedDateTime , replaces the old java.util.Date and SimpleDateFormat , and includes comprehensive support for time zones, offsets, periods, and predefined formatters.

JavaProgrammingAPIDateTimeJava8LocalDate
Architect's Tech Stack
Written by

Architect's Tech Stack

Java backend, microservices, distributed systems, containerized programming, and more.

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.