✅ 一、Java 中的日期类概览

1. java.util.Date(旧版)

  • 表示一个特定的时间点(毫秒值)。
  • 缺点:大部分方法已废弃,线程不安全。
  • 示例:
Date now = new Date();
System.out.println(now);  // 输出类似:Fri Apr 18 10:30:00 CST 2025
  • 1.
  • 2.

2. java.util.Calendar(旧版)

  • Date 功能更多,但依然复杂、不直观。

3. java.time 包(Java 8+ 推荐 ✅)

  • 包含以下重要类:
  • LocalDate:不含时间,表示日期。
  • LocalTime:只包含时间。
  • LocalDateTime:日期+时间。
  • ZonedDateTime:带时区的完整日期时间。
  • Instant:时间戳(UTC 时间)。
  • 示例:
LocalDateTime now = LocalDateTime.now();
System.out.println(now);  // 2025-04-18T10:30:00
  • 1.
  • 2.

✅ 二、日期格式化与解析(字符串 <-> 日期)

1. 使用 SimpleDateFormat(旧版)

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sdf.parse("2025-04-18 10:00:00");
String str = sdf.format(new Date());
  • 1.
  • 2.
  • 3.

2. 使用 DateTimeFormatter(推荐 ✅)

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTime = LocalDateTime.parse("2025-04-18 10:00:00", formatter);
String str = dateTime.format(formatter);
  • 1.
  • 2.
  • 3.

常见格式化符号:

字符

含义

示例

yyyy

2025

MM

月(01~12)

04

dd

日(01~31)

18

HH

小时(00~23)

10

mm

分钟(00~59)

30

ss

秒(00~59)

00


✅ 三、时间戳(Timestamp)

1. 当前时间戳(毫秒数):

long timestamp = System.currentTimeMillis();  // 例如:1713407400000
  • 1.

2. 使用 Instant

Instant now = Instant.now();
long epochMilli = now.toEpochMilli();  // 毫秒时间戳
  • 1.
  • 2.

3. 时间戳转时间:

Instant instant = Instant.ofEpochMilli(1713407400000L);
LocalDateTime time = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
  • 1.
  • 2.

✅ 四、常见用途汇总

场景

推荐方式

获取当前时间

LocalDateTime.now()

格式化为字符串

DateTimeFormatter

字符串转日期

LocalDateTime.parse(...)

获取当前时间戳(毫秒)

System.currentTimeMillis()Instant.now().toEpochMilli()

时间戳转日期

Instant.ofEpochMilli(...).atZone(...)