新的日期和时间API(java.time)
Java 8 引入了全新的日期和时间 API,以解决原有 java.util.Date 和 java.util.Calendar 类的缺点。新的日期时间 API 位于 java.time 包中,提供了更直观、线程安全和不可变的日期时间处理类。
1. 基本日期/时间类
- LocalDate: 表示没有时间的日期,比如生日、纪念日等。
- LocalTime: 表示一天中的时间,不包含日期。
- LocalDateTime: 同时表示日期和时间,但不包含时区信息。
- ZonedDateTime: 表示带有时区的日期和时间。
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.ZoneId;
public class BasicDateTimeExample {
public static void main(String[] args) {
// LocalDate: 表示当前日期
LocalDate today = LocalDate.now(); // 获取当前日期
System.out.println("Today: " + today);
// LocalTime: 表示当前时间
LocalTime now = LocalTime.now(); // 获取当前时间
System.out.println("Current Time: " + now);
// LocalDateTime: 表示当前日期和时间
LocalDateTime currentDateTime = LocalDateTime.now(); // 获取当前日期和时间
System.out.println("Current DateTime: " + currentDateTime);
// ZonedDateTime: 表示带时区的当前日期和时间
ZonedDateTime zonedDateTime = ZonedDateTime.now(); // 获取当前日期和时间,带时区
System.out.println("Current ZonedDateTime: " + zonedDateTime);
// 指定时区的 ZonedDateTime
ZonedDateTime zonedDateTimeInNY = ZonedDateTime.now(ZoneId.of("America/New_York")); // 获取纽约时区的当前日期和时间
System.out.println("ZonedDateTime in New York: " + zonedDateTimeInNY);
}
}
2. 日期/时间的创建
可以通过多种方式创建日期和时间对象,包括指定年、月、日等,或通过解析字符串。
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
import java.time.Month;
public class DateTimeCreationExample {
public static void main(String[] args) {
// 通过指定年、月、日创建 LocalDate
LocalDate date = LocalDate.of(2024, Month.AUGUST, 22); // 创建 2024 年 8 月 22 日的日期对象
System.out.println("Specified Date: " + date);
// 通过指定时、分、秒创建 LocalTime
LocalTime time = LocalTime.of(14, 30, 15); // 创建 14:30:15 的时间对象
System.out.println("Specified Time: " + time);
// 通过指定年、月、日、时、分、秒创建 LocalDateTime
LocalDateTime dateTime = LocalDateTime.of(2024, Month.AUGUST, 22, 14, 30, 15); // 创建 2024 年 8 月 22 日 14:30:15 的日期时间对象
System.out.println("Specified DateTime: " + dateTime);
// 通过解析字符串创建 LocalDate
LocalDate parsedDate = LocalDate.parse("2024-08-22"); // 解析日期字符串
System.out.println("Parsed Date: " + parsedDate);
// 通过解析字符串创建 LocalTime
LocalTime parsedTime = LocalTime.parse("14:30:15"); // 解析时间字符串
System.out.println("Parsed Time: " + parsedTime);
}
}
3. 日期/时间的操作
新的日期时间 API 提供了丰富的方法用于日期和时间的加减、修改。
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
public class DateTimeManipulationExample {
public static void main(String[] args) {
// 创建一个日期对象
LocalDate date = LocalDate.of(2024, 8, 22);
// 增加日期
LocalDate nextWeek = date.plusWeeks(1); // 增加一周
System.out.println("Next Week: " + nextWeek);
// 减少日期
LocalDate lastMonth = date.minusMonths(1); // 减少一个月
System.out.println("Last Month: " + lastMonth);
// 修改日期中的特定部分
LocalDate changedDate = date.withYear(2025); // 修改年份为 2025 年
System.out.println("Changed Year: " + changedDate);
// 操作时间
LocalTime time = LocalTime.of(14, 30);
LocalTime timePlus = time.plusHours(2); // 增加两小时
System.out.println("Time Plus 2 Hours: " + timePlus);
// 操作日期和时间
LocalDateTime dateTime = LocalDateTime.of(2024, 8, 22, 14, 30);
LocalDateTime dateTimeMinus = dateTime.minusDays(5); // 减少 5 天
System.out.println("DateTime Minus 5 Days: " + dateTimeMinus);
}
}
4. 日期/时间的比较
可以使用新的 API 进行日期和时间的比较。
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
public class DateTimeComparisonExample {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
LocalDate futureDate = LocalDate.of(2025, 8, 22);
// 判断日期是否在另一个日期之前
boolean isBefore = today.isBefore(futureDate); // 判断今天是否在指定日期之前
System.out.println("Is today before 2025-08-22? " + isBefore);
// 判断日期是否在另一个日期之后
boolean isAfter = futureDate.isAfter(today); // 判断指定日期是否在今天之后
System.out.println("Is 2025-08-22 after today? " + isAfter);
// 判断时间是否相等
LocalTime now = LocalTime.now();
LocalTime specifiedTime = LocalTime.of(14, 30);
boolean isTimeEqual = now.equals(specifiedTime); // 判断时间是否相等
System.out.println("Is current time equal to 14:30? " + isTimeEqual);
// 日期时间的比较
LocalDateTime dateTime1 = LocalDateTime.of(2024, 8, 22, 14, 30);
LocalDateTime dateTime2 = LocalDateTime.of(2024, 8, 22, 14, 45);
boolean isDateTimeBefore = dateTime1.isBefore(dateTime2); // 判断第一个日期时间是否在第二个之前
System.out.println("Is dateTime1 before dateTime2? " + isDateTimeBefore);
}
}
5. 时区处理
Java 8 提供了对时区的强大支持,可以轻松地在不同时区之间进行转换。
import java.time.ZonedDateTime;
import java.time.ZoneId;
import java.time.LocalDateTime;
public class TimeZoneExample {
public static void main(String[] args) {
// 创建带有默认时区的 ZonedDateTime
ZonedDateTime zonedDateTime = ZonedDateTime.now(); // 当前日期时间,带默认时区
System.out.println("Current ZonedDateTime: " + zonedDateTime);
// 指定时区的 ZonedDateTime
ZoneId newYorkZone = ZoneId.of("America/New_York");
ZonedDateTime newYorkTime = ZonedDateTime.now(newYorkZone); // 当前纽约时间
System.out.println("Current time in New York: " + newYorkTime);
// 将 LocalDateTime 转换为带时区的 ZonedDateTime
LocalDateTime localDateTime = LocalDateTime.of(2024, 8, 22, 14, 30);
ZonedDateTime zonedDateTimeInParis = localDateTime.atZone(ZoneId.of("Europe/Paris")); // 将本地时间转换为巴黎时间
System.out.println("LocalDateTime in Paris: " + zonedDateTimeInParis);
}
}
6. Period 和 Duration
- Period: 表示两个日期之间的间隔,通常用于年月日的计算。
- Duration: 表示两个时间点之间的间隔,通常用于时间的计算。
import java.time.LocalDate;
import java.time.Period;
import java.time.Duration;
import java.time.LocalTime;
public class PeriodDurationExample {
public static void main(String[] args) {
// Period: 计算两个日期之间的间隔
LocalDate startDate = LocalDate.of(2024, 8, 22);
LocalDate endDate = LocalDate.of(2025, 8, 22);
Period period = Period.between(startDate, endDate); // 计算日期间隔
System.out.println("Period: " + period.getYears() + " years " + period
// Period: 计算两个日期之间的间隔
System.out.println("Period: " + period.getYears() + " years " + period.getMonths() + " months " + period.getDays() + " days"); // 打印年、月、日的间隔
// Duration: 计算两个时间之间的间隔
LocalTime startTime = LocalTime.of(14, 30, 0); // 创建起始时间
LocalTime endTime = LocalTime.of(16, 45, 0); // 创建结束时间
Duration duration = Duration.between(startTime, endTime); // 计算时间间隔
System.out.println("Duration: " + duration.toHours() + " hours " + duration.toMinutes() % 60 + " minutes"); // 打印小时和分钟的间隔
}
}
7. 格式化和解析日期时间
Java 8 提供了 DateTimeFormatter 类用于格式化和解析日期时间。
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class DateTimeFormatterExample {
public static void main(String[] args) {
// 获取当前日期时间
LocalDateTime now = LocalDateTime.now();
// 创建格式化器
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); // 定义日期时间格式
// 格式化日期时间
String formattedDateTime = now.format(formatter); // 将当前日期时间格式化为字符串
System.out.println("Formatted DateTime: " + formattedDateTime);
// 解析字符串为日期时间
String dateTimeString = "2024-08-22 14:30:00";
LocalDateTime parsedDateTime = LocalDateTime.parse(dateTimeString, formatter); // 将字符串解析为日期时间对象
System.out.println("Parsed DateTime: " + parsedDateTime);
}
}
总结
Java 8 的新日期时间 API 通过提供不可变对象、线程安全的操作以及更加直观的 API,极大地改善了日期和时间的处理方式。无论是日期时间的创建、操作、比较,还是时区处理、格式化等,都变得更加方便和易于理解。通过上述示例代码,你可以掌握 Java 8 日期时间 API 的基本用法。