Fundamentals 15 min read

Mastering Java 8 Date & Time API: Practical Examples and Code Snippets

This article introduces Java 8's modern date‑time API, explains why the old java.util.Date and SimpleDateFormat are problematic, and provides a series of concise, runnable examples that demonstrate how to obtain the current date, extract year/month/day, work with specific dates, compare dates, handle time zones, calculate periods, format and parse strings, and more.

Java Backend Technology
Java Backend Technology
Java Backend Technology
Mastering Java 8 Date & Time API: Practical Examples and Code Snippets

Java 8 introduced a brand‑new date‑time API (the java.time package) that replaces the mutable, non‑thread‑safe java.util.Date and SimpleDateFormat classes. All classes in java.time are immutable and thread‑safe, and they are based on the ISO calendar system.

Java 8 Date Time API illustration
Java 8 Date Time API illustration

Example 1: Get today’s date

LocalDate

represents a date without a time component. It is immutable and thread‑safe.

package com.shxt.demo02;
import java.time.LocalDate;
public class Demo01 {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        System.out.println("今天的日期:" + today);
    }
}

Example 2: Extract year, month and day

package com.shxt.demo02;
import java.time.LocalDate;
public class Demo02 {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        int year = today.getYear();
        int month = today.getMonthValue();
        int day = today.getDayOfMonth();
        System.out.println("year:" + year);
        System.out.println("month:" + month);
        System.out.println("day:" + day);
    }
}

Example 3: Create a specific date

Use the static factory method LocalDate.of(year, month, day) to create any date.

package com.shxt.demo02;
import java.time.LocalDate;
public class Demo03 {
    public static void main(String[] args) {
        LocalDate date = LocalDate.of(2018, 2, 6);
        System.out.println("自定义日期:" + date);
    }
}

Example 4: Compare two dates for equality

package com.shxt.demo02;
import java.time.LocalDate;
public class Demo04 {
    public static void main(String[] args) {
        LocalDate date1 = LocalDate.now();
        LocalDate date2 = LocalDate.of(2018, 2, 5);
        if (date1.equals(date2)) {
            System.out.println("时间相等");
        } else {
            System.out.println("时间不等");
        }
    }
}

Example 5: Check a recurring event such as a birthday

package com.shxt.demo02;
import java.time.LocalDate;
import java.time.MonthDay;
public class Demo05 {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        LocalDate birthdayDate = LocalDate.of(2018, 2, 6);
        MonthDay birthday = MonthDay.of(birthdayDate.getMonth(), birthdayDate.getDayOfMonth());
        MonthDay current = MonthDay.from(today);
        if (current.equals(birthday)) {
            System.out.println("是你的生日");
        } else {
            System.out.println("你的生日还没有到");
        }
    }
}

Example 6: Get the current time (no date)

package com.shxt.demo02;
import java.time.LocalTime;
public class Demo06 {
    public static void main(String[] args) {
        LocalTime time = LocalTime.now();
        System.out.println("获取当前的时间,不含有日期:" + time);
    }
}

Example 7: Add hours to a time

package com.shxt.demo02;
import java.time.LocalTime;
public class Demo07 {
    public static void main(String[] args) {
        LocalTime time = LocalTime.now();
        LocalTime newTime = time.plusHours(3);
        System.out.println("三个小时后的时间为:" + newTime);
    }
}

Example 8: Calculate the date one week later

package com.shxt.demo02;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class Demo08 {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        System.out.println("今天的日期为:" + today);
        LocalDate nextWeek = today.plus(1, ChronoUnit.WEEKS);
        System.out.println("一周后的日期为:" + nextWeek);
    }
}

Example 9: Compute a date one year before and after today

package com.shxt.demo02;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class Demo09 {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        LocalDate previousYear = today.minus(1, ChronoUnit.YEARS);
        System.out.println("一年前的日期 : " + previousYear);
        LocalDate nextYear = today.plus(1, ChronoUnit.YEARS);
        System.out.println("一年后的日期:" + nextYear);
    }
}

Example 10: Use the Clock class

package com.shxt.demo02;
import java.time.Clock;
public class Demo10 {
    public static void main(String[] args) {
        Clock clock = Clock.systemUTC();
        System.out.println("Clock : " + clock.millis());
        Clock defaultClock = Clock.systemDefaultZone();
        System.out.println("Clock : " + defaultClock.millis());
    }
}

Example 11: Determine whether a date is before or after another date

package com.shxt.demo02;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class Demo11 {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        LocalDate tomorrow = LocalDate.of(2018, 2, 6);
        if (tomorrow.isAfter(today)) {
            System.out.println("之后的日期:" + tomorrow);
        }
        LocalDate yesterday = today.minus(1, ChronoUnit.DAYS);
        if (yesterday.isBefore(today)) {
            System.out.println("之前的日期:" + yesterday);
        }
    }
}

Example 12: Work with time zones

package com.shxt.demo02;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Demo12 {
    public static void main(String[] args) {
        ZoneId america = ZoneId.of("America/New_York");
        LocalDateTime local = LocalDateTime.now();
        ZonedDateTime dateInNY = ZonedDateTime.of(local, america);
        System.out.println("Current date and time in a particular timezone : " + dateInNY);
    }
}

Example 13: Represent a fixed month‑year such as a credit‑card expiry

package com.shxt.demo02;
import java.time.YearMonth;
import java.time.Month;
public class Demo13 {
    public static void main(String[] args) {
        YearMonth current = YearMonth.now();
        System.out.printf("Days in month year %s: %d%n", current, current.lengthOfMonth());
        YearMonth creditCardExpiry = YearMonth.of(2019, Month.FEBRUARY);
        System.out.printf("Your credit card expires on %s %n", creditCardExpiry);
    }
}

Example 14: Check for a leap year

package com.shxt.demo02;
import java.time.LocalDate;
public class Demo14 {
    public static void main(String[] args) {
        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");
        }
    }
}

Example 15: Calculate months between two dates

package com.shxt.demo02;
import java.time.LocalDate;
import java.time.Period;
public class Demo15 {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        LocalDate java8Release = LocalDate.of(2018, 12, 14);
        Period period = Period.between(today, java8Release);
        System.out.println("Months left between today and Java 8 release : " + period.getMonths());
    }
}

Example 16: Get the current timestamp

package com.shxt.demo02;
import java.time.Instant;
public class Demo16 {
    public static void main(String[] args) {
        Instant timestamp = Instant.now();
        System.out.println("What is value of this instant " + timestamp.toEpochMilli());
    }
}

Example 17: Format and parse dates with a predefined formatter

package com.shxt.demo02;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Demo17 {
    public static void main(String[] args) {
        String dayAfterTomorrow = "20180205";
        LocalDate formatted = LocalDate.parse(dayAfterTomorrow, DateTimeFormatter.BASIC_ISO_DATE);
        System.out.println(dayAfterTomorrow + "  格式化后的日期为:  " + formatted);
    }
}

Example 18: Convert between String and date types

package com.shxt.demo02;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Demo18 {
    public static void main(String[] args) {
        LocalDateTime date = LocalDateTime.now();
        DateTimeFormatter format1 = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
        String str = date.format(format1);
        System.out.println("日期转换为字符串:" + str);
        DateTimeFormatter format2 = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
        LocalDate date2 = LocalDate.parse(str, format2);
        System.out.println("日期类型:" + date2);
    }
}
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaprogrammingAPIdatetimejava8exampleslocaldate
Java Backend Technology
Written by

Java Backend Technology

Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!

0 followers
Reader feedback

How this landed with the community

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.