JDK 8 引入的 java.time 包是处理日期时间的首选,比旧的 Date 好用得多。

1. 获取当前日期时间

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;

public class NowDemo {
public static void main(String[] args) {
LocalDate date = LocalDate.now(); // 当前日期(年-月-日)
LocalTime time = LocalTime.now(); // 当前时间(时:分:秒)
LocalDateTime now = LocalDateTime.now(); // 日期 + 时间

System.out.println(date); // 例如 2026-09-05
System.out.println(time); // 例如 20:30:15.123
System.out.println(now); // 例如 2026-09-05T20:30:15.123
}
}

2. 创建指定日期时间

1
2
3
4
5
6
7
8
9
10
11
12
import java.time.LocalDate;
import java.time.LocalDateTime;

public class OfDemo {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2026, 9, 5);
LocalDateTime dt = LocalDateTime.of(2026, 9, 5, 20, 30, 0);

System.out.println(date); // 2026-09-05
System.out.println(dt); // 2026-09-05T20:30
}
}

3. 获取年月日等字段

1
2
3
4
5
6
7
8
9
10
11
12
13
import java.time.LocalDate;

public class GetFieldDemo {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2026, 9, 5);

System.out.println(date.getYear()); // 2026
System.out.println(date.getMonthValue()); // 9
System.out.println(date.getDayOfMonth()); // 5
System.out.println(date.getDayOfWeek()); // SATURDAY
System.out.println(date.getDayOfYear()); // 248
}
}

4. 日期计算(加/减)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import java.time.LocalDate;

public class CalcDemo {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2026, 9, 5);

System.out.println(date.plusDays(10)); // 加 10 天
System.out.println(date.plusMonths(1)); // 加 1 个月
System.out.println(date.plusYears(1)); // 加 1 年
System.out.println(date.minusDays(3)); // 减 3 天

// 比较两个日期
LocalDate other = LocalDate.of(2026, 10, 1);
System.out.println(date.isBefore(other)); // true
System.out.println(date.isAfter(other)); // false
}
}

5. 格式化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class FormatDemo {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();

// 自定义格式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
System.out.println(now.format(formatter)); // 2026-09-05 20:30:15

// 字符串解析成日期
LocalDateTime parsed = LocalDateTime.parse("2026-09-05 20:30:15", formatter);
System.out.println(parsed);
}
}

常用格式符:

格式符 含义 示例
yyyy 年 2026
MM 月(两位) 09
dd 日(两位) 05
HH 时(24 小时制) 20
mm 分 30
ss 秒 15

6. 旧的 Date(了解即可)

1
2
3
4
5
6
7
8
9
10
11
import java.util.Date;

public class DateDemo {
public static void main(String[] args) {
Date date = new Date(); // 当前时间
System.out.println(date); // 例如 Sat Sep 05 20:30:15 CST 2026

long timestamp = date.getTime(); // 毫秒时间戳
System.out.println(timestamp);
}
}

旧项目里可能还有 Date 和 SimpleDateFormat,新代码建议统一用 java.time。

小结

  • 日期用 LocalDate,时间用 LocalTime,都要用 LocalDateTime
  • 格式化/解析用 DateTimeFormatter
  • 日期计算用 plusXxx / minusXxx,比较用 isBefore / isAfter