Master Java 8 Date & Time API: 18 Practical Code Examples
This tutorial introduces Java 8's new date‑time API, explains why the old java.util.Date and SimpleDateFormat were problematic, and demonstrates immutable, thread‑safe classes like LocalDate, LocalTime, LocalDateTime, ZoneId, YearMonth, and Instant through clear, runnable code snippets.
Java 8 introduced a brand‑new date‑time API that addresses long‑standing issues with java.util.Date and SimpleDateFormat, offering immutable and thread‑safe classes under the java.time package.
The new API follows the ISO calendar system and provides clear factories for dates, times, and zones.
Example 1: Get today’s date
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, 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
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
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 date1 = LocalDate.now();
LocalDate date2 = LocalDate.of(2018, 2, 6);
MonthDay birthday = MonthDay.of(date2.getMonth(), date2.getDayOfMonth());
MonthDay currentMonthDay = MonthDay.from(date1);
if (currentMonthDay.equals(birthday)) {
System.out.println("是你的生日");
} else {
System.out.println("你的生日还没有到");
}
}
}Example 6: Get 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 the current 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 a 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: 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: Using Clock to get timestamps
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: Compare dates with isBefore / isAfter
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 localtDateAndTime = LocalDateTime.now();
ZonedDateTime dateAndTimeInNewYork = ZonedDateTime.of(localtDateAndTime, america);
System.out.println("Current date and time in a particular timezone : " + dateAndTimeInNewYork);
}
}Example 13: Represent credit‑card expiry with YearMonth
package com.shxt.demo02;
import java.time.YearMonth;
import java.time.Month;
public class Demo13 {
public static void main(String[] args) {
YearMonth currentYearMonth = YearMonth.now();
System.out.printf("Days in month year %s: %d%n", currentYearMonth, currentYearMonth.lengthOfMonth());
YearMonth creditCardExpiry = YearMonth.of(2019, Month.FEBRUARY);
System.out.printf("Your credit card expires on %s %n", creditCardExpiry);
}
}Example 14: Leap‑year check
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: Days and 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 periodToNextJavaRelease = Period.between(today, java8Release);
System.out.println("Months left between today and Java 8 release : " + periodToNextJavaRelease.getMonths());
}
}Example 16: Get current timestamp with Instant
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: Parse and format dates with predefined formatters
package com.shxt.demo02;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Demo17 {
public static void main(String[] args) {
String dayAfterTommorrow = "20180205";
LocalDate formatted = LocalDate.parse(dayAfterTommorrow, DateTimeFormatter.BASIC_ISO_DATE);
System.out.println(dayAfterTommorrow + " 格式化后的日期为: " + 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);
}
}Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
