当前位置:  首页>> 技术小册>> Java语言基础9-常用API和常见算法

  • Period :表示一段时间的区间,用来度量 年、月、日和几天 之间的时间值。

    • 获取 Period 对象:
  1. public static Period between(LocalDate startDateInclusive, LocalDate endDateExclusive) {}
  • 获取区间相差的年份:
  1. public int getYears() {}
  • 获取区间相差的月份:
  1. public int getMonths() {}
  • 获取区间相差的天数:
  1. public int getDays() {}
  • 获取区间相差总的月份:
  1. public long toTotalMonths() {}
  • Duration :表示时间的区间,用来度量 秒和纳秒 之间的时间值。
    • 获取 Duration 对象:
  1. public static Duration between(Temporal startInclusive, Temporal endExclusive) {}
  • 获取相差的天数:
  1. public long toDays() {}
  • 获取相差的小时:
  1. public long toHours() {}
  • 获取相差的分钟:
  1. public long toMinutes() {}
  • 获取相差的毫秒:
  1. public long toMillis() {}
  • 获取相差的纳秒:
  1. public long toNanos() {}
  • 示例:
  1. package com.github.date.jdk8.demo11;
  2. import java.time.LocalDate;
  3. import java.time.Period;
  4. /**
  5. * @author maxiaoke.com
  6. * @version 1.0
  7. *
  8. */
  9. public class Test {
  10. public static void main(String[] args) {
  11. LocalDate now = LocalDate.now();
  12. System.out.println("now = " + now); // now = 2021-09-27
  13. LocalDate future = LocalDate.now().plusYears(1).plusDays(1).plusMonths(1);
  14. System.out.println("future = " + future); // future = 2022-10-28
  15. Period period = Period.between(now, future);
  16. int years = period.getYears();
  17. System.out.println("区间相差的年 = " + years); // 区间相差的年 = 1,其实就是 future 的year - now的year
  18. int months = period.getMonths();
  19. System.out.println("区间相差的月 = " + months); // 区间相差的月 = 1,其实就是 future 的month - now的month
  20. int days = period.getDays();
  21. System.out.println("区间相差的天 = " + days); // 区间相差的天 = 1,其实就是 future 的day - now的day
  22. long totalMonths = period.toTotalMonths();
  23. System.out.println("区间相差几个月 = " + totalMonths); // 区间相差几个月 = 13,实际相差的月
  24. }
  25. }

示例:

  1. package com.github.date.jdk8.demo12;
  2. import java.time.Duration;
  3. import java.time.LocalDateTime;
  4. /**
  5. * @author maxiaoke.com
  6. * @version 1.0
  7. *
  8. */
  9. public class Test {
  10. public static void main(String[] args) {
  11. LocalDateTime now = LocalDateTime.now();
  12. System.out.println("now = " + now); // now = 2021-09-27T13:29:56.105
  13. LocalDateTime feture = LocalDateTime.now().plusYears(1).plusMonths(1).plusDays(1).plusHours(1).plusMonths(1)
  14. .plusSeconds(1).plusNanos(1);
  15. System.out.println("feture = " + feture); // feture = 2022-11-28T14:29:57.106000001
  16. Duration duration = Duration.between(now, feture);
  17. long seconds = duration.getSeconds();
  18. System.out.println("seconds = " + seconds); // seconds = 36896401
  19. int nano = duration.getNano();
  20. System.out.println("nano = " + nano); // nano = 1000001
  21. }
  22. }