JDK8中时间处理类库
时间类 | 方法 |
LocalDateTime | 时间处理,可精确到纳秒 |
LocalDate | 时间处理,可精确到天 |
LocalDateFormatter | 时间处理,格式化 |
Zoneld | 时区设置类 |
使用SimpleDateFormat进行转换,但是线程不安全。如下所示
- /**
- * 日期格式字符串转日期
- * @param recoure 日期格式字符串
- * @param pattern 日期格式
- *
- * @return
- */
- public static Date strToDate(String recoure, String pattern) {
- try {
- SimpleDateFormat dateTimeFormat = new SimpleDateFormat(pattern);
- return dateTimeFormat.parse(recoure);
- } catch (Exception e) {
- throw new RuntimeException("parse date error");
- }
- }
线程安全
- /**
- * 日期格式字符串转日期 线程安全
- * @param recoure 日期格式字符串
- * @param pattern 日期格式
- *
- * @return
- */
- public static Date strToDate8(String recoure, String pattern) {
- try {
- DateTimeFormatter dateTimeFormat = DateTimeFormatter.ofPattern(pattern);
- if ("yyyy-MM-dd".equals(pattern)) {
- return Date.from(LocalDate.parse(recoure,dateTimeFormat)
- .atStartOfDay()
- .atZone(ZoneId.systemDefault()).toInstant());
- } else {
- return Date.from(LocalDateTime.parse(recoure,dateTimeFormat)
- .atZone(ZoneId.systemDefault()).toInstant());
- }
- } catch (Exception e) {
- throw new BusinessException(ResError.SYS_427);
- }
- }
使用SimpleDateFormat进行转换,但是线程不安全。
- /**
- * 日期转日期格式字符串
- * @param date 日期
- * @param pattern 日期格式
- *
- * @return
- */
- public static String dateToStr(Date date, String pattern) {
- try {
- SimpleDateFormat dateTimeFormat = new SimpleDateFormat(pattern);
- return dateTimeFormat.format(date);
- } catch (Exception e) {
- throw new RuntimeException("parse date error");
- }
- }
- /**
- * LocalDateTime转日期格式字符串 线程安全
- * @param date 日期
- * @param pattern 日期格式
- *
- * @return
- */
- public static String dateToStr8(LocalDateTime date, String pattern) {
- try {
- DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern(pattern);
- return dateFormat.format(date);
- } catch (Exception e) {
- throw new RuntimeException("parse date error");
- }
- }
-
- /**
- * 日期转日期格式字符串 线程安全
- * @param date 日期
- * @param pattern 日期格式
- *
- * @return
- */
- public static String dateToStr8(Date date, String pattern) {
- try {
- DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern(pattern);
- if ("yyyy-MM-dd".equals(pattern)) {
- LocalDate localDate = LocalDateTime
- .ofInstant(date.toInstant(),ZoneId.systemDefault())
- .toLocalDate();
- return dateFormat.format(localDate);
- } else {
- LocalDateTime localDateTime = LocalDateTime
- .ofInstant(date.toInstant(),ZoneId.systemDefault());
- return dateFormat.format(localDateTime);
- }
-
- } catch (Exception e) {
- throw new BusinessException(ResError.SYS_427);
- }
- }
- // LocalDateTime转Date
- LocalDateTime localDateTime = LocalDateTime.now();
- Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
-
- // LocalDate转Date
- LocalDate localDate = LocalDate.now();
- Date date = Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
-
- // Date转LocalDateTime
- Date date = new Date();
- LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(),ZoneId.systemDefault());
-
- // Date转LocalDate
- Date date = new Date();
- LocalDate localDate = LocalDateTime.ofInstant(date.toInstant(),ZoneId.systemDefault()).toLocalDate();
- // LocalDate转String
- LocalDate localDate = LocalDate.now();
- DateTimeFormatter dateTimeFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd");
- String dateStr = localDate.format(dateTimeFormat);
-
- // LocalDateTime转String
- LocalDateTime localDateTime = LocalDateTime.now();
- DateTimeFormatter dateTimeFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
- String dateStr = localDateTime.format(dateTimeFormat);
-
- // String转LocalDate
- String dateStr = "2022-11-07";
- DateTimeFormatter dateTimeFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd");
- LocalDate localDate = LocalDate.parse(dateStr,dateTimeFormat);
-
- // String转LocalDateTime
- String dateStr = "2022-11-07 12:00:00";
- DateTimeFormatter dateTimeFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
- LocalDateTime localDateTime = LocalDateTime.parse(dateStr,dateTimeFormat);
Jdk1.1 之后, 带来了java.util.Calendar工具类, 用于处理时间,格式为【Calendar.getInstance().add(int field, int amount)】;
field为Calendar.DATE表示加减的是天,为Calendar.MONTH表示加减的是月,等;
amount表示加减的日期数,正数表示日期加,负数表示日期减,如下:
- // 三天前
- Calendar calendar1 = Calendar.getInstance();
- calendar1.add(Calendar.DATE, -3);
- System.out.println(calendar1.getTime());
- // 三天后
- Calendar calendar2 = Calendar.getInstance();
- calendar2.add(Calendar.DATE, 3);
- System.out.println(calendar2.getTime());
- // 三分钟后
- Calendar calendar3 = Calendar.getInstance();
- calendar3.add(Calendar.MINUTE, 3);
- System.out.println(calendar3.getTime());
- // 三小时后
- Calendar calendar4 = Calendar.getInstance();
- calendar4.add(Calendar.HOUR, 3);
- System.out.println(calendar4.getTime());
- // 三月后
- Calendar calendar5 = Calendar.getInstance();
- calendar5.add(Calendar.MONTH, 3);
- System.out.println(calendar5.getTime());
操作结果:
- Fri Nov 04 11:06:14 CST 2022
- Thu Nov 10 11:06:14 CST 2022
- Mon Nov 07 11:09:14 CST 2022
- Mon Nov 07 14:06:14 CST 2022
- Tue Feb 07 11:06:14 CST 2023
直接使用LocalDateTime自带的方法即可,如下所示
- DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
- LocalDateTime now = LocalDateTime.now();
- System.out.println("当前时间:"+ now.format(format));
- LocalDateTime plusTime = now.plusMonths(1).plusDays(1).plusHours(1).plusMinutes(1).plusSeconds(1);
- System.out.println("增加1月1天1小时1分钟1秒时间后:" + plusTime.format(format));
- LocalDateTime minusTime = now.minusMonths(1).minusDays(1).minusHours(1).minusMinutes(1).minusSeconds(1);
- System.out.println("减去1月1天1小时1分钟1秒时间后:" + minusTime.format(format));
操作结果:
- 当前时间:2022-11-07 11:14:26
- 增加1月1天1小时1分钟1秒时间后:2022-12-08 12:15:27
- 减去1月1天1小时1分钟1秒时间后:2022-10-06 10:13:25
- LocalDateTime now = LocalDateTime.now();
- LocalDateTime yesterday = now.minusDays(1);
- System.out.println(now + "在" + yesterday + "之后吗?" + now.isAfter(yesterday));
- System.out.println(now + "在" + yesterday + "之前吗?" + now.isBefore(yesterday));
-
- // 时间差
- long day = yesterday.until(now, ChronoUnit.DAYS);
- long month = yesterday.until(now, ChronoUnit.MONTHS);
- long hours = yesterday.until(now, ChronoUnit.HOURS);
- long minutes = yesterday.until(now, ChronoUnit.MINUTES);
- System.out.println("相差月份" + month);
- System.out.println("相差天数" + day);
- System.out.println("相差小时" + hours);
- System.out.println("相差分钟" + minutes);
- /**
- * 获取上周周一(第一天是周一)
- *
- * @return
- */
- public static Date getPreviousMonday() {
- Calendar cal = Calendar.getInstance();
- // 将每周第一天设为星期一,默认是星期天
- cal.setFirstDayOfWeek(Calendar.MONDAY);
- cal.add(Calendar.DATE, -1 * 7);
- cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
-
- cal.set(Calendar.HOUR_OF_DAY, 0);
- cal.set(Calendar.MINUTE, 0);
- cal.set(Calendar.SECOND, 0);
- cal.set(Calendar.MILLISECOND, 0);
- return cal.getTime();
- }
-
- /**
- * 获取上周周日(第一天是周一)
- * @return
- */
- public static Date getLastSunday() {
- Calendar cal = Calendar.getInstance();
- //将每周第一天设为星期一,默认是星期天
- cal.setFirstDayOfWeek(Calendar.MONDAY);
- cal.add(Calendar.DATE, -1*7);
- cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
-
- cal.set(Calendar.HOUR_OF_DAY, 0);
- cal.set(Calendar.MINUTE, 0);
- cal.set(Calendar.SECOND, 0);
- cal.set(Calendar.MILLISECOND, 0);
- return cal.getTime();
- }
- LocalDateTime now = LocalDateTime.now();
- System.out.println("当前时间:" + now);
- // 当天最后一秒
- LocalDateTime lastSecondOfDay = now.withHour(23).withMinute(59).withSecond(59);
- System.out.println("当天最后一秒:" + lastSecondOfDay);
- // 本月第一天
- LocalDateTime firstDay = now.withDayOfMonth(1);
- System.out.println("本月第一天:" + firstDay);
- // 本月最后一天
- LocalDateTime lastDay = now.with(TemporalAdjusters.lastDayOfMonth());
- System.out.println("本月最后一天:" + lastDay);
- // 今日所在周的周一
- LocalDateTime monday = now.with(TemporalAdjusters.previous(DayOfWeek.SUNDAY)).plusDays(1).withHour(0).withMinute(0).withSecond(0);
- System.out.println("今日所在周的周一:" + monday);
- // 今日所在周的周二
- LocalDateTime tuesday = now.with(TemporalAdjusters.previous(DayOfWeek.SUNDAY)).plusDays(2).withHour(0).withMinute(0).withSecond(0);
- System.out.println("今日所在周的周二:" + tuesday);
- // 今日所在周的周日
- LocalDateTime sunday = now.with(TemporalAdjusters.next(DayOfWeek.MONDAY)).minusDays(1).withHour(23).withMinute(59).withSecond(59);
- System.out.println("今日所在周的周日:" + sunday);
- // 今日所在周的上周一
- LocalDateTime lastMonday = now.with(TemporalAdjusters.previous(DayOfWeek.MONDAY));
- System.out.println("今日所在周的上周一:" + lastMonday);
- // 是否闰年
- System.out.println("今年是否闰年:" + Year.isLeap(now.getYear()));
操作结果:
- 当前时间:2022-11-07T11:40:20.377
- 当天最后一秒:2022-11-07T23:59:59.377
- 本月第一天:2022-11-01T11:40:20.377
- 本月最后一天:2022-11-30T11:40:20.377
- 今日所在周的周一:2022-11-07T00:00:00.377
- 今日所在周的周二:2022-11-08T00:00:00.377
- 今日所在周的周日:2022-11-13T23:59:59.377
- 今日所在周的上周一:2022-10-31T11:40:20.377
- 今年是否闰年:false
- /**
- * 获取下一个分钟值以0或者5结尾的时间点(单位:毫秒)
- * @return
- */
- public static long getNextMillisEndWithMinute0or5(Date baseTime) {
- Calendar calendar = Calendar.getInstance();
- calendar.setTime(baseTime);
- int minute = calendar.get(Calendar.MINUTE);
- if (minute < 55) {
- int add = minute%10 < 5? 5 - minute%10 : 10 - minute%10;
- calendar.add(Calendar.MINUTE,add);
- calendar.set(Calendar.SECOND, 0);
- calendar.set(Calendar.MILLISECOND, 0);
- return calendar.getTime().getTime();
- }
- calendar.set(Calendar.MINUTE, 0);
- calendar.set(Calendar.SECOND, 0);
- calendar.set(Calendar.MILLISECOND, 0);
- Date endTime = DateUtils.addHours(calendar.getTime(), 1);
- return endTime.getTime();
- }
-
- /**
- * 获取上一个分钟值以0或者5结尾的时间点(单位:毫秒)
- * @return
- */
- public static long getLastMillisEndWithMinute0or5(Date baseTime) {
- Calendar calendar = Calendar.getInstance();
- calendar.setTime(baseTime);
- int minute = calendar.get(Calendar.MINUTE);
- if (minute < 55) {
- int add = minute%10 < 5? 5 - minute%10 : 10 - minute%10;
- calendar.add(Calendar.MINUTE, -(5-add));
- calendar.set(Calendar.SECOND, 0);
- calendar.set(Calendar.MILLISECOND, 0);
- return calendar.getTime().getTime();
- }
- calendar.set(Calendar.MINUTE, 0);
- calendar.set(Calendar.SECOND, 0);
- calendar.set(Calendar.MILLISECOND, 0);
- Date endTime = DateUtils.addHours(calendar.getTime(), 1);
- return endTime.getTime();
- }
-
- public static String getNextStrTimeEndWithMinute0or5(Date date, String format) {
- if(StringUtil.isEmpty(format)){
- format = "yyyy-MM-dd HH:mm:ss";
- }
- return DateFormatUtils.format(getNextMillisEndWithMinute0or5(date),format);
- }
-
- public static String getLastStrTimeEndWithMinute0or5(Date date, String format) {
- if(StringUtil.isEmpty(format)){
- format = "yyyy-MM-dd HH:mm:ss";
- }
- return DateFormatUtils.format(getLastMillisEndWithMinute0or5(date),format);
- }