Java时间旅行者指南:掌握LocalDate、LocalDateTime、Instant、Duration和Period等

LocalDate LocalDateTime类提供了丰富的方法,但在实际开发场景中,面对特定的问题时,本人和在座的大佬可能会暂时遗忘如何使用相关的 API。因此,这里汇总了常用和较少用到的方法,以便快速参考。

一、LocalDate常用的方法

方法描述例子
now()获取当前日期LocalDate today = LocalDate.now();
of(int year, int month, int dayOfMonth)创建指定年月日的日期LocalDate dateOfBirth = LocalDate.of(1990, 5, 25);
parse(CharSequence text)从文本字符串解析日期LocalDate date = LocalDate.parse("2023-05-20");
plusDays(long daysToAdd)在此日期基础上增加指定的天数LocalDate tomorrow = today.plusDays(1);
minusDays(long daysToSubtract)在此日期基础上减去指定的天数LocalDate yesterday = today.minusDays(1);
plusWeeks(long weeksToAdd)在此日期基础上增加指定的周数LocalDate nextWeek = today.plusWeeks(1);
minusWeeks(long weeksToSubtract)在此日期基础上减去指定的周数LocalDate lastWeek = today.minusWeeks(1);
plusMonths(long monthsToAdd)在此日期基础上增加指定的月数LocalDate nextMonth = today.plusMonths(1);
minusMonths(long monthsToSubtract)在此日期基础上减去指定的月数LocalDate lastMonth = today.minusMonths(1);
plusYears(long yearsToAdd)在此日期基础上增加指定的年数LocalDate nextYear = today.plusYears(1);
minusYears(long yearsToSubtract)在此日期基础上减去指定的年数LocalDate lastYear = today.minusYears(1);
getYear()获取年份int year = today.getYear();
getMonth()获取月份(枚举)Month month = today.getMonth();
getMonthValue()获取月份(数值)int month = today.getMonthValue();
getDayOfMonth()获取月份中的日int day = today.getDayOfMonth();
getDayOfWeek()获取星期中的日(枚举)DayOfWeek dayOfWeek = today.getDayOfWeek();
getDayOfYear()获取年份中的日int dayOfYear = today.getDayOfYear();
isLeapYear()判断是否是闰年boolean isLeap = today.isLeapYear();
withYear(int year)将此日期的年份更改为指定值LocalDate nextYearDate = today.withYear(2024);
withMonth(int month)将此日期的月份更改为指定值LocalDate nextMonthDate = today.withMonth(12);
withDayOfMonth(int dayOfMonth)将此日期的日更改为指定值LocalDate newDate = today.withDayOfMonth(10);
isEqual(LocalDate other)比较两个日期是否相等boolean isEqual = today.isEqual(otherDate);
isBefore(LocalDate other)比较此日期是否在指定日期之前boolean isBefore = today.isBefore(otherDate);
isAfter(LocalDate other)比较此日期是否在指定日期之后boolean isAfter = today.isAfter(otherDate);

二、LocalDate不常用的方法

方法描述例子
atStartOfDay()将此日期与午夜时间(00:00)组合,创建 LocalDateTimeLocalDateTime startOfDay = date.atStartOfDay();
atTime(LocalTime time)将此日期与指定时间组合,创建 LocalDateTimeLocalDateTime dateTime = date.atTime(LocalTime.NOON);
atTime(int hour, int minute)将此日期与指定的小时和分钟组合,创建 LocalDateTimeLocalDateTime dateTime = date.atTime(13, 30);
atTime(int hour, int minute, int second)将此日期与指定的小时、分钟和秒组合,创建 LocalDateTimeLocalDateTime dateTime = date.atTime(13, 30, 15);
atTime(int hour, int minute, int second, int nanoOfSecond)将此日期与指定的小时、分钟、秒和纳秒组合,创建 LocalDateTimeLocalDateTime dateTime = date.atTime(13, 30, 15, 200);
with(TemporalAdjuster adjuster)基于指定的调节器调整日期LocalDate nextMonday = date.with(TemporalAdjusters.next(DayOfWeek.MONDAY)); //下周一
withDayOfYear(int dayOfYear)将此日期的年份中的日更改为指定值LocalDate newDate = date.withDayOfYear(150);
toEpochDay()将此日期转换为从1970-01-01起的天数long count = date.toEpochDay();
lengthOfMonth()返回此日期所在月份的天数int daysInMonth = date.lengthOfMonth();
lengthOfYear()返回此日期所在年份的天数(考虑闰年)int daysInYear = date.lengthOfYear();
until(ChronoLocalDate endDate)计算此日期与另一个日期之间的期间Period period = date.until(endDate);
until(ChronoLocalDate endDate, TemporalUnit unit)计算此日期与另一个日期之间的指定单位的数量long daysBetween = date.until(endDate, ChronoUnit.DAYS);
getChronology()获取此日期的日历系统(可用来操作不同文化和地区日历系统)Chronology chrono = date.getChronology();
getEra()获取此日期的纪元Era era = date.getEra();
isSupported(TemporalUnit unit)检查此日期是否支持指定的时间单位boolean isSupported = date.isSupported(ChronoUnit.DAYS);

三、LocalDateTime常用的方法

以下是 LocalDateTime 类的一些常用方法及示例,整理成表格形式:

方法描述示例
now()获取当前的日期时间LocalDateTime.now()
of(int year, int month, int dayOfMonth, int hour, int minute)创建指定年、月、日、小时、分钟的日期时间LocalDateTime.of(2024, 3, 8, 20, 30)
plusDays(long days)在此日期时间上添加指定的天数LocalDateTime.now().plusDays(5)
minusHours(long hours)在此日期时间上减去指定的小时数LocalDateTime.now().minusHours(2)
getDayOfMonth()获取此日期时间的月份中的日(1-31)LocalDateTime.now().getDayOfMonth()
getMonth()获取此日期时间的月份LocalDateTime.now().getMonth()
getYear()获取此日期时间的年份LocalDateTime.now().getYear()
format(DateTimeFormatter formatter)使用提供的格式化程序格式化此日期时间LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
toLocalDate()将此日期时间转换为 LocalDateLocalDateTime.now().toLocalDate()
toLocalTime()将此日期时间转换为 LocalTimeLocalDateTime.now().toLocalTime()

四、LocalDateTime不常用的方法

方法描述示例
withYear(int year)更改此日期时间的年份LocalDateTime.now().withYear(2022)
withMonth(int month)更改此日期时间的月份LocalDateTime.now().withMonth(12)
withDayOfMonth(int dayOfMonth)更改此日期时间的月份中的日LocalDateTime.now().withDayOfMonth(10)
withHour(int hour)更改此日期时间的小时LocalDateTime.now().withHour(15)
withMinute(int minute)更改此日期时间的分钟LocalDateTime.now().withMinute(45)
withSecond(int second)更改此日期时间的秒数LocalDateTime.now().withSecond(30)
withNano(int nanoOfSecond)更改此日期时间的纳秒数LocalDateTime.now().withNano(500)
atZone(ZoneId zone)将此日期时间与指定的时区组合,生成 ZonedDateTimeLocalDateTime.now().atZone(ZoneId.of("Asia/Tokyo"))
toEpochSecond(ZoneOffset offset)将此日期时间转换为自1970-01-01T00:00:00Z以来的秒数LocalDateTime.now().toEpochSecond(ZoneOffset.UTC)
compareTo(LocalDateTime other)比较两个日期时间的先后LocalDateTime.now().compareTo(LocalDateTime.of(2024, 3, 8, 20, 30))

五、其他

  • Instant:

    • 用途:代表的是一个时间戳,它记录的是从1970年1月1日0时0分0秒(UTC)开始的秒数和纳秒数。
    • 特点:通常用于表示一个具体的时刻,不涉及时区处理,适合用于记录事件的发生时间。
    • 假设你想记录用户点击按钮的确切时间点,你可以使用Instant来实现:
      Instant clickTime = Instant.now();
      System.out.println("Button clicked at: " + clickTime);
      
      这里,clickTime就是一个时间点,表示用户点击按钮的那一刻。
  • Duration:

    • 用途:用于计算两个时间点之间的时间差,其精度可以达到纳秒。
    • 特点:主要用于计算两个Instant对象,或者两个LocalTime对象之间的差距,表示以秒和纳秒为单位的时间量。
    • 现在,假设你想计算用户在两次点击之间停留的时间,你可以使用Duration来计算这两个时间点之间的差异:
      Instant firstClick = Instant.now();
      // 假设用户在一段时间后再次点击
      Instant secondClick = Instant.now().plusSeconds(120); // 假定2分钟后再次点击
      
      Duration timeBetweenClicks = Duration.between(firstClick, secondClick);
      System.out.println("Time between clicks: " + timeBetweenClicks.getSeconds() + " seconds");
      
      在这个例子中,timeBetweenClicks表示用户两次点击之间的时间间隔,以秒为单位。
  • Period:

    • 用途:用于计算两个日期之间的年、月、日数。
    • 特点:与Duration不同,Period计算的是以年、月、日为单位的时间量,主要用于LocalDate之间的日期差计算。
    • 假设你想计算一个人的年龄,即从出生日期到当前日期的年月日数,你可以使用Period来计算:
      LocalDate birthDate = LocalDate.of(1990, 5, 15);
      LocalDate currentDate = LocalDate.now();
      
      Period age = Period.between(birthDate, currentDate);
      System.out.println("You are " + age.getYears() + " years, " + age.getMonths() + " months, and " + age.getDays() + " days old.");
      
      这里,age表示从出生日期到当前日期的完整年、月、日数,用于表示一个人的年龄。

总结其区别:

  • 精度不同InstantDuration更关注精确时间点和精确时间长度,精度可达纳秒;而Period关注的是以年月日计算的较为宽泛的时间段。
  • 使用场景不同Instant用于时间戳记录,Duration用于计算具体时间长度,Period用于计算日期间隔。
  • 适用对象不同Duration适用于时刻和时间长度的计算,通常与InstantLocalTime配合使用;Period专用于日期的计算,通常与LocalDate配合使用。

Java 8引入了一系列改进的时间和日期处理类,其中除了InstantDurationPeriod,还有以下几个重要的类:

  • LocalTime:

    • 用途:表示没有日期和时区的时间,如小时、分钟、秒。
    • 示例:记录当前时间。
      LocalTime now = LocalTime.now();
      System.out.println("Current time: " + now);
      
  • ZonedDateTime:

    • 用途:表示带时区的完整日期和时间。
    • 示例:记录一个在不同时区的国际会议时间。
      ZonedDateTime meetingInNY = ZonedDateTime.of(2024, 3, 8, 14, 30, 0, 0, ZoneId.of("America/New_York"));
      System.out.println("Meeting in New York: " + meetingInNY);
      
  • OffsetDateTime:

    • 用途:类似于ZonedDateTime,但使用的是UTC偏移量而不是时区ID。
    • 示例:记录时间和相对于UTC的偏移。
    • 示例:记录时间和相对于UTC的偏移量。
      OffsetDateTime eventTime = OffsetDateTime.of(2024, 3, 8, 14, 30, 0, 0, ZoneOffset.ofHours(2));
      System.out.println("Event time (UTC+2): " + eventTime);
      
  • DateTimeFormatter:

    • 用途:用于自定义日期和时间的格式化和解析。
    • 示例:格式化日期时间显示。
      LocalDateTime now = LocalDateTime.now();
      DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
      String formattedDateTime = now.format(formatter);
      System.out.println("Formatted date and time: " + formattedDateTime);
      
  • ChronoUnit:

    • 用途:枚举类,用于在时间日期计算中指定时间单位。
    • 示例:计算两个日期之间的天数。
      LocalDate startDate = LocalDate.of(2023, 1, 1);
      LocalDate endDate = LocalDate.of(2024, 1, 1);
      long daysBetween = ChronoUnit.DAYS.between(startDate, endDate);
      System.out.println("Days between: " + daysBetween);
      
  • 15
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值