Java 8 Date and Time API: Practical Examples and Usage
This tutorial demonstrates how Java 8's new immutable, thread‑safe date‑time API (java.time) can be used to obtain the current date, extract year/month/day, create specific dates, compare dates, handle time zones, format and parse strings, and perform common date‑time calculations with clear code examples.
Java 8 introduced a new date‑time API (java.time) that is immutable and thread‑safe, addressing the shortcomings of java.util.Date and SimpleDateFormat.
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: Get 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
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 (without 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 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: Calculate 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 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 if 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: Working 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: Representing fixed dates such as 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: Checking 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: Calculating 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: Getting the 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: Parsing a date string 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: Converting 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 Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java 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.
