Common Java 8 Date and Time APIs: Getting Today’s Date and More
This article demonstrates how to use Java 8’s java.time package to obtain the current date and time, extract components, create specific dates, compare dates, handle periodic dates, compute future and past dates, retrieve timestamps, check leap years, calculate differences, and format/parse date strings, with concrete code examples.
Java 8 introduced the java.time package, which provides a comprehensive set of classes for handling dates and times. The article walks through practical usages of these core classes.
Getting the current date and extracting its parts:
// Get today's date
System.out.println("今天的日期是:" + LocalDate.now());
// Extract year, month, day
System.out.println("获取年月日信息是:" + LocalDate.now().getYear() + "年" + LocalDate.now().getMonthValue() + "月" + LocalDate.now().getDayOfMonth() + "日");Creating a specific date and comparing dates for equality:
// Create a specific date (2022-10-18)
LocalDate specificLocalDate = LocalDate.of(2022, 10, 18);
System.out.println("创建特定日期是:" + specificLocalDate);
// Equality checks
System.out.println(LocalDate.now().equals(LocalDate.of(2022, 10, 18))); // false
System.out.println(LocalDate.now().equals(LocalDate.now())); // trueChecking periodic dates such as birthdays or annual inspections using MonthDay:
// Is today October 17?
System.out.println(MonthDay.of(LocalDate.now().getMonth(), LocalDate.now().getDayOfMonth()).equals(MonthDay.of(10, 17))); // true
// Is today October 18?
System.out.println(MonthDay.of(LocalDate.now().getMonth(), LocalDate.now().getDayOfMonth()).equals(MonthDay.of(10, 18))); // falseObtaining the current time and adding offsets:
// Current time
System.out.println("当前时间为:" + LocalTime.now());
// Add 5 hours, 5 minutes, 5 seconds
System.out.println("当前时间为:" + LocalTime.now() + "当前时间往后5个小时为" + LocalTime.now().plusHours(5));
System.out.println("当前时间为:" + LocalTime.now() + "当前时间往后5分钟为" + LocalTime.now().plusMinutes(5));
System.out.println("当前时间为:" + LocalTime.now() + "当前时间往后5秒钟为" + LocalTime.now().plusSeconds(5));Calculating future dates with ChronoUnit:
// One week later
System.out.println("当前日期为:" + LocalDate.now() + "当前日期一周后为:" + LocalDate.now().plus(1, ChronoUnit.WEEKS));
// One day later
System.out.println("当前日期为:" + LocalDate.now() + "当前日期一天后为:" + LocalDate.now().plus(1, ChronoUnit.DAYS));
// One month later
System.out.println("当前日期为:" + LocalDate.now() + "当前日期一月后为:" + LocalDate.now().plus(1, ChronoUnit.MONTHS));
// One year later
System.out.println("当前日期为:" + LocalDate.now() + "当前日期一年后为:" + LocalDate.now().plus(1, ChronoUnit.YEARS));Calculating past dates using minus with the same units:
// One week ago
System.out.println("当前日期为:" + LocalDate.now() + "当前日期一周前为:" + LocalDate.now().minus(1, ChronoUnit.WEEKS));
// One day ago
System.out.println("当前日期为:" + LocalDate.now() + "当前日期一天前为:" + LocalDate.now().minus(1, ChronoUnit.DAYS));
// One month ago
System.out.println("当前日期为:" + LocalDate.now() + "当前日期一月前为:" + LocalDate.now().minus(1, ChronoUnit.MONTHS));
// One year ago
System.out.println("当前日期为:" + LocalDate.now() + "当前日期一年前为:" + LocalDate.now().minus(1, ChronoUnit.YEARS));Retrieving timestamps in milliseconds:
// UTC timestamp
System.out.println("systemUTC当前时间戳为:" + Clock.systemUTC().millis());
// Default zone timestamp
System.out.println("systemDefaultZone当前时间戳为:" + Clock.systemDefaultZone().millis());
// Instant timestamp
System.out.println("当前时间戳为:" + Instant.now().toEpochMilli());Comparing dates with isBefore and isAfter:
System.out.println("当前日期:" + LocalDate.now() + "是否早于2022-10-18:" + LocalDate.now().isBefore(LocalDate.of(2022, 10, 18)));
System.out.println("当前日期:" + LocalDate.now() + "是否晚于2022-10-18:" + LocalDate.now().isAfter(LocalDate.of(2022, 10, 18)));Leap‑year check :
System.out.println("今年是否为闰年:" + LocalDate.now().isLeapYear());Calculating differences :
// Separate year/month/day difference using Period
Period between = Period.between(LocalDate.now(), LocalDate.of(2033, 12, 30));
System.out.println("当前距离2033-12-30相差" + between.getYears() + "年" + between.getMonths() + "月" + between.getDays() + "日");
// Total difference in various units using until
System.out.println("当前距离2033-12-30总共相差天数:" + LocalDate.now().until(LocalDate.of(2033, 12, 30), ChronoUnit.DAYS));
System.out.println("当前距离2033-12-30总共相差周数:" + LocalDate.now().until(LocalDate.of(2033, 12, 30), ChronoUnit.WEEKS));
System.out.println("当前距离2033-12-30总共相差月数:" + LocalDate.now().until(LocalDate.of(2033, 12, 30), ChronoUnit.MONTHS));
System.out.println("当前距离2033-12-30总共相差年数:" + LocalDate.now().until(LocalDate.of(2033, 12, 30), ChronoUnit.YEARS));Formatting and parsing between strings and date/time objects:
// Parse a basic ISO date string
System.out.println("格式化20221017后的日期为:" + LocalDate.parse("20221017", DateTimeFormatter.BASIC_ISO_DATE));
// Convert LocalDateTime to a formatted string
System.out.println("日期转换为字符串为:" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss")));
// Parse a formatted string back to a date
System.out.println("字符串转换为日期:" + LocalDate.parse("2022/12/17 19:22:42", DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss")));Each code fragment prints the result as a comment in the original source, illustrating the exact output one would see when running the examples.
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.
The Dominant Programmer
Resources and tutorials for programmers' advanced learning journey. Advanced tracks in Java, Python, and C#. Blog: https://blog.csdn.net/badao_liumang_qizhi
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.
