1. LocalDate:无时间和时区的日期
LocalDate 就是一个纯日期。没有时间,没有时区,也没有额外麻烦。就像日历上的一页:2025-06-01——仅此而已。如果你不关心不同城市“午夜”何时到来,而只是需要“2025 年 6 月 1 日”,请使用 LocalDate。
如何创建 LocalDate?
有多种方式,都很简单易用。
当前日期
import java.time.LocalDate;
LocalDate today = LocalDate.now();
System.out.println(today); // 例如,2025-06-01
指定日期
LocalDate birthday = LocalDate.of(1990, 12, 15);
System.out.println(birthday); // 1990-12-15
可以为年、月、日传入数字。月份是 1 到 12 的数字(1 — 一月,12 — 十二月)。
从字符串解析
LocalDate parsedDate = LocalDate.parse("2025-06-01");
System.out.println(parsedDate); // 2025-06-01
字符串必须是 yyyy-MM-dd 格式。如果格式不匹配,将抛出异常。
获取日期的各个组成部分
LocalDate 提供了返回日期各部分的方法:
int year = today.getYear(); // 2025
int month = today.getMonthValue(); // 6(六月)
int day = today.getDayOfMonth(); // 1
System.out.println("年: " + year + ", 月: " + month + ", 日: " + day);
如果想要月份的英文名称,请使用 getMonth() 方法:
System.out.println(today.getMonth()); // JUNE
如果需要星期几,请使用 getDayOfWeek() 方法:
System.out.println(today.getDayOfWeek()); // SATURDAY
实践示例
继续扩展你的学习用控制台应用:现在它可以向用户发送生日祝贺。
import java.time.LocalDate;
public class BirthdayApp {
public static void main(String[] args) {
LocalDate birthday = LocalDate.of(2000, 2, 29);
System.out.println("出生日期: " + birthday);
System.out.println("出生那天的星期: " + birthday.getDayOfWeek());
}
}
2. LocalTime:无日期和时区的时间
LocalTime 是纯时间:时、分、秒(甚至纳秒),但没有日期!当你需要保存“商店的开门时间”或“会议开始时间”等且不关心日期时,这个类就很合适。
如何创建 LocalTime?
当前时间
import java.time.LocalTime;
LocalTime now = LocalTime.now();
System.out.println(now); // 例如,14:37:12.123456789
指定时间
LocalTime lunchTime = LocalTime.of(13, 30); // 13:30:00
System.out.println(lunchTime);
也可以添加秒和纳秒:
LocalTime precise = LocalTime.of(8, 15, 30, 123_000_000); // 08:15:30.123
System.out.println(precise);
从字符串解析
LocalTime parsedTime = LocalTime.parse("14:30:00");
System.out.println(parsedTime); // 14:30
获取时间的各个组成部分
int hour = now.getHour();
int minute = now.getMinute();
int second = now.getSecond();
System.out.println("小时: " + hour + ", 分钟: " + minute + ", 秒: " + second);
实践示例
在我们的应用中添加一个“时钟”:
import java.time.LocalTime;
public class ClockApp {
public static void main(String[] args) {
LocalTime current = LocalTime.now();
System.out.println("现在: " + current);
System.out.println("小时: " + current.getHour());
System.out.println("分钟: " + current.getMinute());
}
}
3. LocalDateTime:无时区的日期和时间
LocalDateTime 是组合:日期 + 时间,但仍然没有时区。例如,“2025-06-01 14:30:00”。当你要保存一个时间点却不关心读这个时间的人所处的地理位置时,它很方便。
如何创建 LocalDateTime?
当前日期和时间
import java.time.LocalDateTime;
LocalDateTime now = LocalDateTime.now();
System.out.println(now); // 例如,2025-06-01T14:30:15.123456789
指定日期和时间
LocalDateTime meeting = LocalDateTime.of(2025, 6, 1, 14, 30);
System.out.println(meeting); // 2025-06-01T14:30
也可以添加秒和纳秒:
LocalDateTime preciseMeeting = LocalDateTime.of(2025, 6, 1, 14, 30, 45, 123_000_000);
System.out.println(preciseMeeting); // 2025-06-01T14:30:45.123
从字符串解析
LocalDateTime parsed = LocalDateTime.parse("2025-06-01T14:30:00");
System.out.println(parsed); // 2025-06-01T14:30
请注意:按照 ISO 标准,字母 T 用来把日期与时间分隔开。
获取各个组成部分
int year = now.getYear();
int month = now.getMonthValue();
int day = now.getDayOfMonth();
int hour = now.getHour();
int minute = now.getMinute();
System.out.println("日期: " + year + "-" + month + "-" + day + " 时间: " + hour + ":" + minute);
4. 日期和时间的常见操作
现在我们已经会创建日期与时间对象了,来学习一些有用的操作。
加减运算
这三个类(LocalDate、LocalTime、LocalDateTime)都是不可变的。这意味着 plusDays() 或 minusMonths() 这类方法会返回新的对象,而不会修改原对象。
LocalDate
LocalDate today = LocalDate.now();
LocalDate tomorrow = today.plusDays(1);
LocalDate lastMonth = today.minusMonths(1);
System.out.println("今天: " + today);
System.out.println("明天: " + tomorrow);
System.out.println("一个月前: " + lastMonth);
LocalTime
LocalTime now = LocalTime.now();
LocalTime inTenMinutes = now.plusMinutes(10);
System.out.println("现在: " + now);
System.out.println("10 分钟后: " + inTenMinutes);
LocalDateTime
LocalDateTime start = LocalDateTime.of(2025, 6, 1, 14, 0);
LocalDateTime end = start.plusHours(2).minusMinutes(15);
System.out.println("开始: " + start);
System.out.println("结束: " + end);
日期和时间的比较
所有这些类都提供了 isBefore()、isAfter()、isEqual() 方法:
LocalDate birthday = LocalDate.of(2000, 2, 29);
LocalDate today = LocalDate.now();
if (today.isAfter(birthday)) {
System.out.println("你已经比刚出生时年长了!");
}
LocalTime morning = LocalTime.of(8, 0);
LocalTime now = LocalTime.now();
if (now.isBefore(morning)) {
System.out.println("现在起床还太早...");
} else {
System.out.println("该起床了!");
}
获取当前的日期/时间
如你所见,now() 方法会返回当前值:
LocalDate date = LocalDate.now();
LocalTime time = LocalTime.now();
LocalDateTime dateTime = LocalDateTime.now();
5. 实践:示例与练习
示例 1:任意日期的星期几
import java.time.LocalDate;
public class DayOfWeekApp {
public static void main(String[] args) {
LocalDate anyDate = LocalDate.of(2025, 12, 31);
System.out.println("2025 年 12 月 31 日 是 " + anyDate.getDayOfWeek());
}
}
示例 2:距离新年还有多少天?
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class DaysToNewYear {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
LocalDate newYear = LocalDate.of(today.getYear() + 1, 1, 1);
long daysLeft = ChronoUnit.DAYS.between(today, newYear);
System.out.println("距离新年还有 " + daysLeft + " 天!");
}
}
示例 3:检查是否为闰年
import java.time.LocalDate;
public class LeapYearCheck {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2025, 1, 1);
if (date.isLeapYear()) {
System.out.println(date.getYear() + " 是闰年!");
} else {
System.out.println(date.getYear() + " 是平年。");
}
}
}
示例 4:两个时间之间的差值
import java.time.LocalTime;
import java.time.Duration;
public class TimeDifference {
public static void main(String[] args) {
LocalTime start = LocalTime.of(9, 0);
LocalTime end = LocalTime.of(17, 30);
Duration duration = Duration.between(start, end);
System.out.println("工作日持续 " + duration.toHours() + " 小时 " +
(duration.toMinutes() % 60) + " 分钟。");
}
}
6. 常见错误
错误 №1:混淆 LocalDateTime 与 ZonedDateTime。
LocalDateTime 不包含时区信息!如果你在保存跨国航班计划或在不同时区发生的事件——请使用 ZonedDateTime,否则在系统间传输数据时可能得到意料之外的结果。
错误 №2:使用了错误的字符串格式来解析。
例如,试图用 LocalDate.parse() 解析 01.06.2025。默认期望格式是 2025-06-01。对于其他格式,需要专用的 DateTimeFormatter(这将在下一讲介绍!)。
错误 №3:以为 plusDays() 这类方法会修改对象。
不会!所有对象都是不可变的。方法会返回一个新对象,原对象保持不变。
错误 №4:用 LocalTime 存储绝对时间。
LocalTime 只表示本地的一天中的时间。如果你要保存“时间点”,请使用 Instant 或 ZonedDateTime。
错误 №5:忘记了月份编号的差异(1 — 一月,12 — 十二月)。
在 LocalDate.of(year, month, day) 中,月份从 1 开始计数(而不是从 0 开始,某些其他语言或旧 API 是从 0 开始)。
GO TO FULL VERSION