GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — 日期类 · ningtiao/JavaLearning@0218731

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • Basics
    • Java基础之日期类.md
    • demo/datetime
      • s01_query
        • ReportQueryDemo$Order.class
        • ReportQueryDemo.class
        • ReportQueryDemo.java
      • s02_business
        • OrderTimeoutDemo$Order.class
        • OrderTimeoutDemo.class
        • OrderTimeoutDemo.java
      • s03_timezone
        • TimeZoneDemo$1User.class
        • TimeZoneDemo.class
        • TimeZoneDemo.java
      • s04_legacy
        • ThreadSafetyDemo.class
        • ThreadSafetyDemo.java
      • s05_util
        • DateUtils$Range.class
        • DateUtils.class
        • DateUtils.java
        • DateUtilsDemo.class
        • DateUtilsDemo.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎Basics/Java基础之日期类.md‎

Copy file name to clipboard
+264Lines changed: 264 additions & 0 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,264 @@
1+
# Java 基础之日期类
2+
3+
> 只列重点。输出均在 **JDK 21.0.11 / Asia/Shanghai** 实测。
4+
> 一句话结论:**新项目只用 `java.time`,老 API 只在对接遗留代码时碰。**
5+
6+
---
7+
8+
## 1. 两套 API
9+
10+
| | 老 API(JDK 1.0 / 1.1) | 新 API(JDK 8+,JSR-310) |
11+
|---|---|---|
12+
| 类 | `Date`、`Calendar`、`SimpleDateFormat` | `LocalDate`、`LocalDateTime`、`Instant` 等 |
13+
| 可变性 | **可变**,到处传递会被改 | **不可变**,线程安全 |
14+
| 线程安全 | `SimpleDateFormat` **不安全** | 全部安全,`DateTimeFormatter` 可做静态常量 |
15+
| 月份 | **0 开始**(0=一月) | 1 开始(1=一月) |
16+
| 年份 | `Date` 构造里要减 1900 | 正常年份 |
17+
| 时区 | 混在 `Date` 里,语义不清 | 类型上区分有/无时区 |
18+
| 非法日期 | 默认**静默进位** | 直接抛异常 |
19+
20+
---
21+
22+
## 2. 新 API 核心类(按「要不要时区」挑)
23+
24+
| 类 | 含什么 | 典型用途 |
25+
|---|---|---|
26+
| `LocalDate` | 年月日 | 生日、入职日、账期 |
27+
| `LocalTime` | 时分秒 | 营业时间、闹钟 |
28+
| `LocalDateTime` | 年月日时分秒,**无时区** | 本地业务时间、不跨时区的记录 |
29+
| `Instant` | 时间线上的一个瞬间(UTC 时间戳) | 日志时间、埋点、数据库存储 |
30+
| `ZonedDateTime` | `LocalDateTime` + 时区 + 偏移 | 跨时区展示、会议时间 |
31+
| `OffsetDateTime` | `LocalDateTime` + 固定偏移 | API 接口传输(比 Zoned 更稳) |
32+
| `Duration` | **时间量**(秒/纳秒) | 耗时、超时、间隔 |
33+
| `Period` | **日期量**(年/月/日) | 年龄、合同期限 |
34+
| `DayOfWeek` / `Month` | 枚举 | 判断周末、月份逻辑 |
35+
| `YearMonth` / `MonthDay` | 年月 / 月日 | 信用卡有效期、纪念日 |
36+
37+
**选型口诀**:
38+
- 只关心「哪一天」→ `LocalDate`
39+
- 存库、算先后、对外传 → `Instant` 或 `OffsetDateTime`
40+
- 要给用户看本地时间 → `ZonedDateTime`
41+
- **别用 `LocalDateTime` 存跨时区的数据**(它不带时区,比较和换算都会错)
42+
43+
---
44+
45+
## 3. 常用操作速查
46+
47+
### 创建
48+
49+
```java
50+
LocalDate.now(); // 当前日期
51+
LocalDate.of(2024, 2, 10); // 指定(月份就是 2,不是 1)
52+
LocalDate.parse("2024-02-10"); // ISO 格式直接解析,无需 formatter
53+
LocalDateTime.of(2024, 2, 10, 13, 5, 0);
54+
Instant.now();
55+
ZonedDateTime.now(ZoneId.of("Asia/Shanghai"));
56+
```
57+
58+
### 取值 / 判断
59+
60+
```java
61+
d.getYear(); d.getMonthValue(); d.getDayOfMonth(); // getMonth() 返回枚举,getMonthValue() 返回 int
62+
d.getDayOfWeek(); // DayOfWeek.SATURDAY
63+
d.isLeapYear(); // true
64+
d.lengthOfMonth(); // 2024-02 -> 29
65+
d.isBefore(other); d.isAfter(other); d.isEqual(other);
66+
```
67+
68+
### 加减(返回新对象,**必须接住返回值**)
69+
70+
```java
71+
d.plusDays(7); d.minusMonths(1); d.plusYears(1);
72+
d.withDayOfMonth(1); // 改成本月 1 号
73+
d.with(TemporalAdjusters.lastDayOfMonth()); // 2024-02-10 -> 2024-02-29
74+
d.with(TemporalAdjusters.next(DayOfWeek.MONDAY)); // 2024-02-10 -> 2024-02-12
75+
d.with(TemporalAdjusters.firstDayOfNextMonth());
76+
```
77+
78+
实测:`base.plusDays(10)` 后 `base` **没变**,还是 `2024-05-01`。
79+
80+
### 计算差值
81+
82+
```java
83+
ChronoUnit.DAYS.between(a, b); // 推荐,语义明确
84+
ChronoUnit.YEARS.between(birth, today); // 算年龄:1990-05-20 → 2026-11-27 = 36
85+
Period.between(a, b); // 得「几年几月几天」
86+
Duration.between(t1, t2); // 得秒/纳秒,用于耗时
87+
```
88+
89+
### 格式化 / 解析
90+
91+
```java
92+
// DateTimeFormatter 线程安全,做成静态常量复用
93+
static final DateTimeFormatter FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
94+
95+
String s = dateTime.format(FMT);
96+
LocalDateTime t = LocalDateTime.parse("2024-02-10 13:05:00", FMT);
97+
DateTimeFormatter.ISO_LOCAL_DATE; // 内置常量,2024-02-10
98+
```
99+
100+
### 时区转换
101+
102+
```java
103+
Instant i = Instant.now();
104+
ZonedDateTime z = i.atZone(ZoneId.of("Asia/Shanghai"));
105+
Instant back = z.toInstant();
106+
LocalDateTime ldt = z.toLocalDateTime(); // 丢掉时区信息
107+
Instant i2 = ldt.atZone(ZoneId.systemDefault()).toInstant(); // 补上时区才能转回去
108+
```
109+
110+
---
111+
112+
## 4. 格式化模式字母(最容易写错的四对)
113+
114+
| 字母 | 含义 | 写错的后果 |
115+
|---|---|---|
116+
| `yyyy` | 年 | 正确 |
117+
| **`YYYY`** | **周基准年** | 跨年周会错一年 |
118+
| `MM` | 月 | 正确 |
119+
| **`mm`** | **分钟** | `MM` 写成 `mm` 月份变分钟 |
120+
| `HH` | 24 小时制 | 正确 |
121+
| **`hh`** | **12 小时制** | 下午 13:05 显示成 01:05 |
122+
| `dd` | 月中的天 | 正确 |
123+
| `DD` | **一年中的第几天** | 2 月 10 日变成 41 |
124+
125+
实测(`2024-12-30`):
126+
127+
```
128+
yyyy-MM-dd -> 2024-12-30 正确
129+
YYYY-MM-dd -> 2025-12-30 年份错了!
130+
YYYY-ww -> 2025-01 它把这天算成 2025 年第 1 周
131+
HH:mm 对 13:05 -> 13:05
132+
hh:mm 对 13:05 -> 01:05 丢了上下午
133+
MM/mm 对 1月5分 -> 01/05 一模一样,看不出来
134+
```
135+
136+
`YYYY` 的坑最阴:一年里只有年末那几天会错,测试期间几乎碰不到,到了 12 月底突然出事。**日常格式化一律用小写 `yyyy`。**
137+
138+
---
139+
140+
## 5. 必知的坑
141+
142+
### 5.1 `SimpleDateFormat` 不是线程安全的
143+
144+
- 内部用成员变量 `Calendar` 存中间状态,多线程共用会**解析出错误日期**或抛异常
145+
- 做成 `static` 常量是最常见的生产事故写法
146+
- 老代码里的三种救法:每次 new(浪费)、`ThreadLocal` 包一层、换成 `DateTimeFormatter`
147+
148+
### 5.2 老 API 月份从 0 开始
149+
150+
```java
151+
Calendar.JANUARY == 0; Calendar.DECEMBER == 11;
152+
calendar.set(2024, 1, 1); // 实测得到 2024-02-01,不是 1 月
153+
```
154+
155+
`new Date(2024, 1, 1)` 更离谱:年份要传 `年-1900`,已废弃。
156+
157+
### 5.3 非法日期被静默修正
158+
159+
```java
160+
new SimpleDateFormat("yyyy-MM-dd").parse("2023-02-30")
161+
// 实测 -> Thu Mar 02 2023 悄悄进位,不报错
162+
LocalDate.of(2023, 2, 29)
163+
// -> DateTimeException: Invalid date 'February 29' as '2023' is not a leap year
164+
```
165+
166+
老 API 必须 `setLenient(false)` 才会报错。新 API 默认严格。
167+
168+
### 5.4 月末加月份不可逆
169+
170+
```java
171+
LocalDate.of(2024,1,31).plusMonths(1) // 2024-02-29 被截断
172+
LocalDate.of(2024,1,31).plusMonths(1).plusMonths(1) // 2024-03-29
173+
LocalDate.of(2024,1,31).plusMonths(2) // 2024-03-31 和上面不一样!
174+
```
175+
176+
**加月份不满足结合律。** 算分期、订阅续费时要么一次性加够月数,要么明确定义「月末对齐」规则。
177+
178+
### 5.5 `Period` 和 `Duration` / `ChronoUnit` 不是一回事
179+
180+
```java
181+
// 2024-01-31 到 2024-03-01
182+
Period.between(...) // P1M1D getDays() = 1
183+
ChronoUnit.DAYS.between(...) // 30 真实天数
184+
Duration.ofHours(50).toDays() // 2 整除截断,不是 2.08
185+
```
186+
187+
`Period.getDays()` 只是「零头的天数」,**不是总天数**。要总天数用 `ChronoUnit.DAYS.between`。
188+
189+
### 5.6 `LocalDateTime` 不带时区
190+
191+
- 它表示「挂钟时间」,两个 `LocalDateTime` 比较大小,默认假设在同一时区
192+
- 存库、跨服务传递、排序,都该用 `Instant` / `OffsetDateTime`
193+
- 实测:`Instant` 的 UTC `2024-06-01T00:00` 在上海是 `2024-06-01T08:00+08:00`,差 8 小时
194+
195+
### 5.7 其他零散
196+
197+
- `Date` 的 `getYear()`/`getMonth()` 等方法全部废弃,别用
198+
- `java.sql.Date` 继承 `java.util.Date` 但**丢掉时间部分**,`toInstant()` 直接抛异常
199+
- `System.currentTimeMillis()` 会随系统时间调整跳变,**测耗时要用 `System.nanoTime()`**
200+
- 时区用 `ZoneId.of("Asia/Shanghai")`,不要用已废弃的三字母缩写 `CST`(有四种含义)
201+
202+
---
203+
204+
## 6. 新旧 API 互转
205+
206+
```java
207+
// 老 -> 新
208+
Instant i = date.toInstant();
209+
LocalDateTime ldt = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
210+
211+
// 新 -> 老
212+
Date d = Date.from(instant);
213+
Date d2 = Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());
214+
215+
// 时间戳
216+
long ms = instant.toEpochMilli();
217+
Instant i2 = Instant.ofEpochMilli(ms);
218+
long sec = instant.getEpochSecond();
219+
```
220+
221+
关键:**`LocalDateTime` 和 `Instant` 互转必须补时区**,这是转换代码最常出错的地方。
222+
223+
---
224+
225+
## 7. 实战片段
226+
227+
```java
228+
// 今天的起止(查当日数据)
229+
LocalDateTime start = LocalDate.now().atStartOfDay(); // 00:00:00
230+
LocalDateTime end = LocalDate.now().plusDays(1).atStartOfDay(); // 用左闭右开,别用 23:59:59
231+
232+
// 本月第一天 / 最后一天
233+
LocalDate first = today.withDayOfMonth(1);
234+
LocalDate last = today.with(TemporalAdjusters.lastDayOfMonth());
235+
236+
// 算年龄
237+
int age = (int) ChronoUnit.YEARS.between(birthday, LocalDate.now());
238+
239+
// 判断周末
240+
boolean weekend = EnumSet.of(DayOfWeek.SATURDAY, DayOfWeek.SUNDAY).contains(d.getDayOfWeek());
241+
242+
// 超时判断
243+
if (Duration.between(createTime, Instant.now()).toMinutes() > 30) { /* 订单超时 */ }
244+
245+
// 遍历日期区间(JDK 9+)
246+
start.datesUntil(end).forEach(System.out::println);
247+
```
248+
249+
> 查区间数据用 **左闭右开** `[start, start+1天)`,不要用 `23:59:59` —— 会漏掉最后一秒内的毫秒级数据。
250+
251+
---
252+
253+
## 8. 检查清单
254+
255+
- [ ] 格式化用的是小写 `yyyy` 而不是 `YYYY`?
256+
- [ ] 小时是 `HH`(24 小时制)还是误写成 `hh`?
257+
- [ ] 月份是 `MM` 而不是 `mm`?
258+
- [ ] 还有 `static SimpleDateFormat` 吗?换掉
259+
- [ ] 加减日期的返回值接住了吗(不可变对象)?
260+
- [ ] 算总天数用的是 `ChronoUnit.DAYS.between`,不是 `Period.getDays()`?
261+
- [ ] 跨时区的数据用的是 `Instant`/`OffsetDateTime`,不是 `LocalDateTime`?
262+
- [ ] `LocalDateTime` ↔ `Instant` 转换时指定时区了吗?
263+
- [ ] 查区间是左闭右开,还是写了 `23:59:59`?
264+
- [ ] 测耗时用的是 `nanoTime()` 还是 `currentTimeMillis()`?
Collapse file

‎Basics/demo/datetime/s01_query/ReportQueryDemo$Order.class‎

Copy file name to clipboard
1.81 KB
Binary file not shown.
Collapse file

‎Basics/demo/datetime/s01_query/ReportQueryDemo.class‎

Copy file name to clipboard
14.9 KB
Binary file not shown.

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.