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)组合,创建 LocalDateTime | LocalDateTime startOfDay = date.atStartOfDay(); |
atTime(LocalTime time) | 将此日期与指定时间组合,创建 LocalDateTime | LocalDateTime dateTime = date.atTime(LocalTime.NOON); |
atTime(int hour, int minute) | 将此日期与指定的小时和分钟组合,创建 LocalDateTime | LocalDateTime dateTime = date.atTime(13, 30); |
atTime(int hour, int minute, int second) | 将此日期与指定的小时、分钟和秒组合,创建 LocalDateTime | LocalDateTime dateTime = date.atTime(13, 30, 15); |
atTime(int hour, int minute, int second, int nanoOfSecond) | 将此日期与指定的小时、分钟、秒和纳秒组合,创建 LocalDateTime | LocalDateTime 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() | 将此日期时间转换为 LocalDate | LocalDateTime.now().toLocalDate() |
toLocalTime() | 将此日期时间转换为 LocalTime | LocalDateTime.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) | 将此日期时间与指定的时区组合,生成 ZonedDateTime | LocalDateTime.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
表示从出生日期到当前日期的完整年、月、日数,用于表示一个人的年龄。
总结其区别:
- 精度不同:
Instant
和Duration
更关注精确时间点和精确时间长度,精度可达纳秒;而Period
关注的是以年月日计算的较为宽泛的时间段。 - 使用场景不同:
Instant
用于时间戳记录,Duration
用于计算具体时间长度,Period
用于计算日期间隔。 - 适用对象不同:
Duration
适用于时刻和时间长度的计算,通常与Instant
或LocalTime
配合使用;Period
专用于日期的计算,通常与LocalDate
配合使用。
Java 8引入了一系列改进的时间和日期处理类,其中除了Instant
、Duration
和Period
,还有以下几个重要的类:
-
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);