java时间类-深入探究DateUtils的最佳实践
解锁Java时间操作的秘密武器:深入探究DateUtils的最佳实践
1、造轮子?只有工程师才会造轮子,所以我们都是工程师。
2、时间一个啥子东西呢,抓不住,留不住,但是我们可以记住。
前文回顾
1.为什么 Java 中的时间类如此繁多而复杂?
2.如何摆脱Java旧版时间类的困扰?Java 8新时间API带你轻松玩转时间
3.Java时间类- 还不会用Java8中java.time类选择使用场景吗?
4.Java时间类-java.time时间类常见操作工具集
我们基于java.time封装一个完整的 DateUtils
工具类,结合了之前提到的所有功能,支持多种常见的时间处理场景,并兼容 Date
类型和字符串类型的输入。
深入浅出探究其功能点
- 时间获取: 获取当前日期、时间或日期时间。
- 时间格式化: 支持将
LocalDateTime
,LocalDate
,LocalTime
,Date
转换为指定格式的字符串,默认格式为yyyy-MM-dd HH:mm:ss
。 - 字符串解析: 支持将字符串解析为
LocalDateTime
,LocalDate
,LocalTime
,以及自动识别并处理Date
。 - 日期时间加减: 支持对日期时间进行加减操作,包括天数、小时、分钟和秒数等,兼容
Date
和字符串输入。 - 时间区间计算: 计算两个时间点之间的时间差,可以是天数或秒数,兼容
Date
类型。 - 旧类
Date
的兼容: 提供Date
与java.time
API 之间的转换,方便处理老的时间类。 - 时间戳操作: 获取当前时间戳,将时间戳转换为
LocalDateTime
,或者将LocalDateTime
转换为时间戳。
废话不多说,上代码,皇阿码
DateUtils
工具类
package com.example.utils;import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Date;
/*** v 一周一志程序员* @author zhizhou 2024/10/09 16:07*/
public class DateUtils {// 默认时间格式private static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";private static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";private static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";// 格式化器private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT);private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT);private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT);// 获取当前时间public static LocalDateTime getCurrentDateTime() {return LocalDateTime.now();}public static LocalDate getCurrentDate() {return LocalDate.now();}public static LocalTime getCurrentTime() {return LocalTime.now();}// 日期转字符串public static String formatDateTime(LocalDateTime dateTime) {return dateTime.format(DATE_TIME_FORMATTER);}public static String formatDateTime(Date date) {return formatDateTime(toLocalDateTime(date));}public static String formatDate(LocalDate date) {return date.format(DATE_FORMATTER);}public static String formatDate(Date date) {return formatDate(toLocalDate(date));}public static String formatTime(LocalTime time) {return time.format(TIME_FORMATTER);}public static String formatTime(Date date) {return formatTime(toLocalDateTime(date).toLocalTime());}// 字符串转日期public static LocalDateTime parseDateTime(String dateTimeStr) {return LocalDateTime.parse(dateTimeStr, DATE_TIME_FORMATTER);}public static LocalDate parseDate(String dateStr) {return LocalDate.parse(dateStr, DATE_FORMATTER);}public static LocalTime parseTime(String timeStr) {return LocalTime.parse(timeStr, TIME_FORMATTER);}// 日期加减操作public static LocalDateTime addDays(LocalDateTime dateTime, long days) {return dateTime.plusDays(days);}public static LocalDateTime addDays(Date date, long days) {return addDays(toLocalDateTime(date), days);}public static LocalDateTime addHours(LocalDateTime dateTime, long hours) {return dateTime.plusHours(hours);}public static LocalDateTime addHours(Date date, long hours) {return addHours(toLocalDateTime(date), hours);}public static LocalDateTime addMinutes(LocalDateTime dateTime, long minutes) {return dateTime.plusMinutes(minutes);}public static LocalDateTime addMinutes(Date date, long minutes) {return addMinutes(toLocalDateTime(date), minutes);}public static LocalDateTime addSeconds(LocalDateTime dateTime, long seconds) {return dateTime.plusSeconds(seconds);}public static LocalDateTime addSeconds(Date date, long seconds) {return addSeconds(toLocalDateTime(date), seconds);}// 时间区间计算public static long betweenDates(LocalDate startDate, LocalDate endDate) {return ChronoUnit.DAYS.between(startDate, endDate);}public static long betweenDates(Date startDate, Date endDate) {return betweenDates(toLocalDate(startDate), toLocalDate(endDate));}public static long betweenDateTimes(LocalDateTime startDateTime, LocalDateTime endDateTime) {return ChronoUnit.SECONDS.between(startDateTime, endDateTime);}public static long betweenDateTimes(Date startDateTime, Date endDateTime) {return betweenDateTimes(toLocalDateTime(startDateTime), toLocalDateTime(endDateTime));}// 转换成旧的 Date 类public static Date toDate(LocalDateTime dateTime) {ZoneId zone = ZoneId.systemDefault();ZonedDateTime zdt = dateTime.atZone(zone);return Date.from(zdt.toInstant());}public static Date toDate(LocalDate date) {return Date.from(date.atStartOfDay(ZoneId.systemDefault()).toInstant());}// 将 Date 转 LocalDateTimepublic static LocalDateTime toLocalDateTime(Date date) {Instant instant = date.toInstant();return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());}// 将 Date 转 LocalDatepublic static LocalDate toLocalDate(Date date) {return toLocalDateTime(date).toLocalDate();}// 将字符串或 Date 转 LocalDateTimepublic static LocalDateTime toLocalDateTime(String dateTimeStr) {return parseDateTime(dateTimeStr);}public static LocalDateTime toLocalDateTime(Object dateOrString) {if (dateOrString instanceof Date) {return toLocalDateTime((Date) dateOrString);} else if (dateOrString instanceof String) {return parseDateTime((String) dateOrString);} else {throw new IllegalArgumentException("Unsupported type. Must be Date or String.");}}// 获取当前时间戳public static long getCurrentTimestamp() {return Instant.now().getEpochSecond();}// 时间戳转换为 LocalDateTimepublic static LocalDateTime timestampToLocalDateTime(long timestamp) {return LocalDateTime.ofEpochSecond(timestamp, 0, ZoneOffset.UTC);}// LocalDateTime 转时间戳public static long toTimestamp(LocalDateTime dateTime) {return dateTime.toEpochSecond(ZoneOffset.UTC);}
}
用用看
public class TestDateUtils {public static void main(String[] args) {// 获取当前时间LocalDateTime now = DateUtils.getCurrentDateTime();System.out.println("当前时间: " + DateUtils.formatDateTime(now));// 字符串解析为日期时间LocalDateTime dateTimeFromString = DateUtils.toLocalDateTime("2024-10-09 12:30:45");System.out.println("解析的日期时间: " + dateTimeFromString);// Date 转 LocalDateTimeDate nowDate = new Date();LocalDateTime dateTimeFromDate = DateUtils.toLocalDateTime(nowDate);System.out.println("Date 转换为 LocalDateTime: " + dateTimeFromDate);// 日期加减操作LocalDateTime tomorrow = DateUtils.addDays(nowDate, 1);System.out.println("明天的此刻: " + DateUtils.formatDateTime(tomorrow));// 时间戳操作long currentTimestamp = DateUtils.getCurrentTimestamp();System.out.println("当前时间戳: " + currentTimestamp);LocalDateTime fromTimestamp = DateUtils.timestampToLocalDateTime(currentTimestamp);System.out.println("时间戳转换为日期时间: " + DateUtils.formatDateTime(fromTimestamp));}
}
通过这种改造,DateUtils
现在可以处理更多类型的时间输入,提高了工具类的灵活性和兼容性。善用 DateUtils
,不只是优化代码,更是让我们对生活与工作的每一秒都心中有数。时间不再难以驾驭, DateUtils
让这一切变得有章可循。技术的发展让我们得以创造,而时间管理的优化,则让我们在纷繁复杂的世界里,掌控自己的节奏。
时间一个啥东西,抓不住,留不住,但是我们可以记住。
时间一个啥东西,抓不住,留不住,但是它见证了我们的成长。