Java 8 java.time

本文最后更新于 2024年4月15日 下午

Introducion

Java 8 中引入了 java.time 包,其中包含了一组全新的日期时间类,用于替代旧的 java.util.Datejava.util.Calendar 类。新的日期时间类提供了更丰富、更灵活和更易于使用的功能,同时修复了旧的日期时间设计中存在的一些缺陷,比如线程不安全性、可变性、构造日期的 year 和 month 设计不合理。

Class Hierarchy

  • LocalDate: 表示一个日期,不包含时间信息。
  • LocalTime: 表示一个时间,不包含日期信息。
  • LocalDateTime: 表示日期和时间,不包含时区信息。
  • ZonedDateTime: 表示日期、时间和时区信息。
  • Duration: 表示一个时间段,以秒和纳秒为单位。
  • Period: 表示一个日期段,以年、月、日为单位。
  • DateTimeFormatter:日期时间格式化。

In practice

LocalDate

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class LocalDateExample {
public static void main(String[] args) {
// 创建指定日期
LocalDate date = LocalDate.of(2022, 4, 10);
System.out.println("Specified date: " + date);

// 解析日期字符串
String dateString = "2022-04-10";
LocalDate parsedDate = LocalDate.parse(dateString);
System.out.println("Parsed date: " + parsedDate);

// 使用自定义格式解析日期字符串
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
LocalDate customParsedDate = LocalDate.parse("2022/04/10", formatter);
System.out.println("Custom parsed date: " + customParsedDate);
}
}

LocalTime

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

public class LocalTimeExample {
public static void main(String[] args) {
// 创建指定时间
LocalTime time = LocalTime.of(15, 30, 45);
System.out.println("Specified time: " + time);

// 解析时间字符串
String timeString = "15:30:45";
LocalTime parsedTime = LocalTime.parse(timeString);
System.out.println("Parsed time: " + parsedTime);
}
}

LocalDateTime

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

public class LocalDateTimeExample {
public static void main(String[] args) {
// 创建指定日期和时间
LocalDateTime dateTime = LocalDateTime.of(2022, 4, 10, 15, 30, 45);
System.out.println("Specified date and time: " + dateTime);

// 解析日期时间字符串
String dateTimeString = "2022-04-10T15:30:45";
LocalDateTime parsedDateTime = LocalDateTime.parse(dateTimeString);
System.out.println("Parsed date and time: " + parsedDateTime);
}
}

DateTimeFormatter

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

public class DateTimeFormatterExample {
public static void main(String[] args) {
// 创建当前日期和时间
LocalDateTime now = LocalDateTime.now();

// 创建自定义格式的 DateTimeFormatter
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

// 格式化日期时间
String formattedDateTime = now.format(formatter);
System.out.println("Formatted date and time: " + formattedDateTime);

// 解析日期时间字符串
LocalDateTime parsedDateTime = LocalDateTime.parse(formattedDateTime, formatter);
System.out.println("Parsed date and time: " + parsedDateTime);
}
}

Java 8 java.time
https://stein283036.github.io/2024/04/15/Java-8-java-time/
作者
倪京龙
发布于
2024年4月15日
更新于
2024年4月15日
许可协议