写在前面:时间来也匆匆,去也匆匆。匆匆那年,今夕何年。不知你我,不懂你我。且走且行且看,人生求得大。观。圆。
时间操作是软件开发中的常见需求,尤其是在处理业务逻辑和用户界面时。以下是常见的时间操作以及它们的使用场景:
前文回顾
1.为什么 Java 中的时间类如此繁多而复杂?
2.如何摆脱Java旧版时间类的困扰?Java 8新时间API带你轻松玩转时间
3.Java时间类- 还不会用Java8中java.time类选择使用场景吗?
一、获取当前时间
获取当前日期和时间是最常见的时间操作之一。在 Java 8 及以上版本中,可以使用 LocalDate
, LocalTime
, LocalDateTime
, ZonedDateTime
等类。
-
获取当前日期
LocalDate currentDate = LocalDate.now();
-
获取当前时间
LocalTime currentTime = LocalTime.now();
-
获取当前日期和时间
LocalDateTime currentDateTime = LocalDateTime.now();
-
获取带时区的当前日期时间
ZonedDateTime currentZonedDateTime = ZonedDateTime.now(ZoneId.of("America/New_York"));
二、 日期/时间加减
需要对日期或时间进行加减操作,比如将某个日期加上几天,或者减去几小时。在 Java 8 中,这种操作非常简便。
-
加/减天数
LocalDate tomorrow = LocalDate.now().plusDays(1); // 明天 LocalDate lastWeek = LocalDate.now().minusWeeks(1); // 上周
-
加/减小时
LocalTime inTwoHours = LocalTime.now().plusHours(2); // 2小时后 LocalTime oneHourAgo = LocalTime.now().minusHours(1); // 1小时前
-
加/减日期和时间
LocalDateTime nextWeek = LocalDateTime.now().plusWeeks(1); // 一周后 LocalDateTime lastMonth = LocalDateTime.now().minusMonths(1); // 一个月前
三、日期和时间比较
在处理时间范围或检查两个时间是否相等时,日期和时间的比较操作非常重要。
-
判断日期时间是否在某个区间内
LocalDate date = LocalDate.of(2023, 10, 10); boolean isBefore = date.isBefore(LocalDate.now()); // 判断是否在当前日期之前 boolean isAfter = date.isAfter(LocalDate.now()); // 判断是否在当前日期之后
-
比较两个日期的先后顺序
LocalDate date1 = LocalDate.of(2023, 1, 1); LocalDate date2 = LocalDate.of(2024, 1, 1); int comparison = date1.compareTo(date2); // 返回负数表示 date1 在 date2 之前
四、计算日期/时间间隔
计算两个时间点之间的差值(时间间隔)是常见操作,比如计算用户某个操作持续了多长时间。
-
计算日期间隔(以年、月、日为单位)
LocalDate startDate = LocalDate.of(2023, 1, 1); LocalDate endDate = LocalDate.of(2023, 10, 10); Period period = Period.between(startDate, endDate); System.out.println("Years: " + period.getYears() + " Months: " + period.getMonths() + " Days: " + period.getDays());
-
计算时间间隔(以秒或纳秒为单位)
LocalTime startTime = LocalTime.of(10, 30); LocalTime endTime = LocalTime.of(12, 45); Duration duration = Duration.between(startTime, endTime); System.out.println("Duration in minutes: " + duration.toMinutes());
-
计算精确到时分秒的间隔
LocalDateTime startDateTime = LocalDateTime.of(2023, 10, 10, 10, 30); LocalDateTime endDateTime = LocalDateTime.of(2023, 10, 10, 12, 45); Duration duration = Duration.between(startDateTime, endDateTime); System.out.println("Duration in hours: " + duration.toHours());
五、时间格式化与解析
格式化和解析时间字符串是处理用户输入、日志记录和展示的常见需求。Java 8 提供了 DateTimeFormatter
,可以自定义日期和时间的格式。
-
格式化日期
LocalDate date = LocalDate.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); String formattedDate = date.format(formatter); System.out.println(formattedDate); // 输出:2023-10-10
-
格式化时间
LocalTime time = LocalTime.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss"); String formattedTime = time.format(formatter); System.out.println(formattedTime); // 输出:10:30:45
-
解析日期字符串
String dateString = "2023-10-10"; LocalDate parsedDate = LocalDate.parse(dateString, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
-
解析时间字符串
String timeString = "10:30:45"; LocalTime parsedTime = LocalTime.parse(timeString, DateTimeFormatter.ofPattern("HH:mm:ss"));
六、处理时区
在处理国际化的应用程序时,时区问题不可避免。Java 8 的 ZonedDateTime
提供了对不同时区的支持。
-
获取特定时区的时间
ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of("America/New_York"));
-
将本地时间转换为特定时区
ZonedDateTime localZonedDateTime = ZonedDateTime.now(); ZonedDateTime newYorkTime = localZonedDateTime.withZoneSameInstant(ZoneId.of("America/New_York"));
七、处理时间戳
时间戳表示某个时间点自 Unix 纪元(1970 年 1 月 1 日 00:00:00 UTC)以来的秒或毫秒数,通常用于系统日志或时间标记。
-
获取当前时间戳
Instant timestamp = Instant.now(); System.out.println("Current timestamp: " + timestamp);
-
将时间戳转换为日期时间
Instant timestamp = Instant.now(); LocalDateTime dateTime = LocalDateTime.ofInstant(timestamp, ZoneId.systemDefault());
-
将日期时间转换为时间戳
LocalDateTime dateTime = LocalDateTime.now(); Instant timestamp = dateTime.toInstant(ZoneOffset.UTC);
八、转换旧的时间类
在 Java 8 之前,java.util.Date
和 java.util.Calendar
是处理时间的主力类。为了兼容旧代码,可以将它们转换为新版时间类。
-
Date
转换为LocalDate
Date date = new Date(); LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
-
Calendar
转换为LocalDateTime
Calendar calendar = Calendar.getInstance(); LocalDateTime localDateTime = LocalDateTime.ofInstant(calendar.toInstant(), ZoneId.systemDefault());
九、时间段处理
需要处理一段时间(如工作时间段或活动时间段)时,可以使用 Java 8 的时间 API 来表示起始和结束时间。
-
表示时间段的开始和结束
LocalDateTime start = LocalDateTime.of(2023, 10, 10, 9, 0); LocalDateTime end = LocalDateTime.of(2023, 10, 10, 17, 0); boolean isWithinPeriod = now.isAfter(start) && now.isBefore(end);
十、 处理夏令时
夏令时是跨时区处理时必须考虑的问题。ZonedDateTime
自动处理夏令时转换。
-
自动处理夏令时
ZonedDateTime zonedDateTime = ZonedDateTime.of(2024, 3, 31, 1, 59, 59, 0, ZoneId.of("Europe/London")); ZonedDateTime nextMinute = zonedDateTime.plusMinutes(1); // 会自动跳到夏令时
总结
Java 8 的 java.time
API 为日期和时间操作提供了丰富的工具,涵盖了从获取当前时间、日期计算、时间格式化到处理时区、时间戳等多种常见需求。通过使用这些类,开发者可以更简洁、安全、准确地进行时间操作。