现代java日期时间处理推荐使用java.time包。1. 核心类包括localdate、localtime、localdatetime、zoneddatetime和instant,分别表示日期、时间、日期时间、带时区的日期时间和时间戳;2. 所有类均为不可变对象,保证线程安全;3. 通过now()和of()方法创建实例,支持链式调用进行加减操作;4. 使用datetimeformatter进行日期时间的格式化与解析,需注意模式匹配和locale设置;5. duration用于计算以秒或纳秒为单位的时间差,period用于计算以年、月、日为单位的日期差;6. 时区通过zoneid和zoneddatetime处理,支持跨时区转换。该api设计清晰、语义明确、线程安全,彻底解决了旧date和calendar类的诸多缺陷,是java日期时间操作的现代标准解决方案。

Java处理日期时间,现在主流且推荐的方式是使用
java.time
java.util.Date
Calendar
Date
Calendar
java.time
要高效且优雅地处理Java中的日期时间,核心就是拥抱并熟练运用
java.time
LocalDate
LocalTime
LocalDateTime
我个人觉得,理解这几个核心类的区别是第一步。当你需要处理“今天是什么日子”时,用
LocalDate
LocalTime
LocalDateTime
ZonedDateTime
Instant
立即学习“Java免费学习笔记(深入)”;
这些类都是不可变(immutable)的,这意味着一旦创建,它们的值就不能被改变。所有修改日期时间的操作(比如加一天、减一小时)都会返回一个新的实例,这大大提升了代码的线程安全性,也避免了许多潜在的bug。这在多线程环境下简直是个福音,你再也不用担心某个线程不小心改了共享的日期对象而导致混乱。
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
// 获取当前日期
LocalDate today = LocalDate.now();
System.out.println("今天: " + today); // 例如: 2023-10-26
// 获取当前时间
LocalTime nowTime = LocalTime.now();
System.out.println("现在时间: " + nowTime); // 例如: 15:30:45.123
// 获取当前日期时间
LocalDateTime nowDateTime = LocalDateTime.now();
System.out.println("当前日期时间: " + nowDateTime); // 例如: 2023-10-26T15:30:45.123
// 创建指定日期
LocalDate specificDate = LocalDate.of(2023, 1, 15);
System.out.println("指定日期: " + specificDate);
// 创建指定日期时间
LocalDateTime specificDateTime = LocalDateTime.of(2023, 10, 26, 10, 30, 0);
System.out.println("指定日期时间: " + specificDateTime);
// 加上几天/几小时
LocalDate nextWeek = today.plusWeeks(1);
System.out.println("下周今天: " + nextWeek);
LocalDateTime nextHour = nowDateTime.plusHours(1);
System.out.println("一小时后: " + nextHour);
// 减去几天/几小时
LocalDate yesterday = today.minusDays(1);
System.out.println("昨天: " + yesterday);
// 格式化日期时间
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
String formattedDateTime = nowDateTime.format(formatter);
System.out.println("格式化后的日期时间: " + formattedDateTime); // 例如: 2023年10月26日 15:30:45
// 解析字符串为日期时间
String dateString = "2024-05-20 13:14:00";
DateTimeFormatter parser = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime parsedDateTime = LocalDateTime.parse(dateString, parser);
System.out.println("解析后的日期时间: " + parsedDateTime);
// 处理时区
ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of("America/New_York"));
System.out.println("纽约当前时间: " + zonedDateTime);
// 时间戳 Instant
Instant timestamp = Instant.now();
System.out.println("当前时间戳: " + timestamp.toEpochMilli()); // 毫秒级时间戳说实话,Java早期处理日期时间的那一套,
java.util.Date
java.util.Calendar
Date
Calendar
java.time
首先是不可变性。所有的日期时间对象一旦创建,就不能被修改。任何对日期时间的“修改”操作,比如
plusDays()
minusHours()
其次是清晰的语义。
LocalDate
LocalTime
LocalDateTime
ZonedDateTime
Instant
再来是流畅的API设计。链式调用变得非常自然,比如
LocalDate.now().plusDays(7).minusMonths(1)
isAfter()
isBefore()
isLeapYear()
最后,对时区处理的支持也做得非常完善。
ZoneId
ZonedDateTime
Calendar
所以,拥抱
java.time
光知道
java.time
创建: 除了上面提到的
now()
of()
parse()
// 从字符串创建(默认ISO_LOCAL_DATE格式)
LocalDate parsedLocalDate = LocalDate.parse("2023-11-01");
System.out.println("从字符串解析的日期: " + parsedLocalDate);
// 从字符串创建(默认ISO_LOCAL_DATE_TIME格式)
LocalDateTime parsedLocalDateTime = LocalDateTime.parse("2023-11-01T10:00:00");
System.out.println("从字符串解析的日期时间: " + parsedLocalDateTime);需要注意的是,
parse()
DateTimeFormatter
DateTimeFormatter
格式化: 这可是个高频操作。
java.time
DateTimeFormatter
// 预定义格式
LocalDateTime current = LocalDateTime.now();
String basicIsoDate = current.format(DateTimeFormatter.BASIC_ISO_DATE); // 20231026
String isoLocalDateTime = current.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME); // 2023-10-26T15:30:45.123
System.out.println("Basic ISO Date: " + basicIsoDate);
System.out.println("ISO Local Date Time: " + isoLocalDateTime);
// 自定义模式
DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss EEEE", java.util.Locale.CHINA);
String customFormatted = current.format(customFormatter);
System.out.println("自定义格式: " + customFormatted); // 例如: 2023/10/26 15:30:45 星期四
// 注意Locale的使用,这对于国际化非常重要,比如星期几的显示这里有个小细节,
ofPattern()
Locale
解析: 解析就是格式化的逆过程,把字符串变回日期时间对象。同样需要
DateTimeFormatter
String dateStringForParse = "2025年01月01日 12:00:00";
DateTimeFormatter parserToUse = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
try {
LocalDateTime parsedAgain = LocalDateTime.parse(dateStringForParse, parserToUse);
System.out.println("再次解析的日期时间: " + parsedAgain);
} catch (java.time.format.DateTimeParseException e) {
System.err.println("日期字符串格式不匹配: " + e.getMessage());
// 这里可以处理解析失败的情况,比如给用户提示或者记录日志
}解析时,字符串的格式必须和
DateTimeFormatter
DateTimeParseException
在实际开发中,我们经常需要计算两个日期之间相隔多久,或者一个时间点过去/未来多少时间。
java.time
Duration
Period
Duration
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
Instant startInstant = Instant.now();
// 模拟一些耗时操作
try {
Thread.sleep(2500); // 暂停2.5秒
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
Instant endInstant = Instant.now();
Duration timeElapsed = Duration.between(startInstant, endInstant);
System.out.println("操作耗时 (秒): " + timeElapsed.getSeconds()); // 大约2秒
// 创建一个指定时长的Duration
Duration threeHours = Duration.ofHours(3);
LocalDateTime futureTime = LocalDateTime.now().plus(threeHours);
System.out.println("三小时后: " + futureTime);Duration
toDays()
toHours()
toMinutes()
getSeconds()
Period
import java.time.Period;
import java.time.LocalDate;
LocalDate startDate = LocalDate.of(2022, 1, 15);
LocalDate endDate = LocalDate.of(2023, 10, 26);
Period period = Period.between(startDate, endDate);
System.out.println("相隔年数: " + period.getYears()); // 1
System.out.println("相隔月数: " + period.getMonths()); // 9
System.out.println("相隔天数: " + period.getDays()); // 11
System.out.println("总共相隔: " + period.getYears() + "年" + period.getMonths() + "月" + period.getDays() + "天");
// 创建一个指定周期的Period
Period oneYearTwoMonths = Period.ofYears(1).plusMonths(2);
LocalDate futureDate = LocalDate.now().plus(oneYearTwoMonths);
System.out.println("一年两个月后: " + futureDate);Period
一个常见的误区是混淆
Duration
Period
LocalDateTime
Duration
LocalDate
Period
以上就是java使用教程如何进行日期时间的处理 java使用教程的日期操作实用方法的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号