• Java处理日期


    前言

    JDK8中时间处理类库

    时间类方法
    LocalDateTime时间处理,可精确到纳秒
    LocalDate时间处理,可精确到天
    LocalDateFormatter时间处理,格式化
    Zoneld时区设置类

    日期格式字符串转日期

    • JDK8之前

    使用SimpleDateFormat进行转换,但是线程不安全。如下所示

    1. /**
    2. * 日期格式字符串转日期
    3. * @param recoure 日期格式字符串
    4. * @param pattern 日期格式
    5. *
    6. * @return
    7. */
    8. public static Date strToDate(String recoure, String pattern) {
    9. try {
    10. SimpleDateFormat dateTimeFormat = new SimpleDateFormat(pattern);
    11. return dateTimeFormat.parse(recoure);
    12. } catch (Exception e) {
    13. throw new RuntimeException("parse date error");
    14. }
    15. }
    • JDK8之后

    线程安全

    1. /**
    2. * 日期格式字符串转日期 线程安全
    3. * @param recoure 日期格式字符串
    4. * @param pattern 日期格式
    5. *
    6. * @return
    7. */
    8. public static Date strToDate8(String recoure, String pattern) {
    9. try {
    10. DateTimeFormatter dateTimeFormat = DateTimeFormatter.ofPattern(pattern);
    11. if ("yyyy-MM-dd".equals(pattern)) {
    12. return Date.from(LocalDate.parse(recoure,dateTimeFormat)
    13. .atStartOfDay()
    14. .atZone(ZoneId.systemDefault()).toInstant());
    15. } else {
    16. return Date.from(LocalDateTime.parse(recoure,dateTimeFormat)
    17. .atZone(ZoneId.systemDefault()).toInstant());
    18. }
    19. } catch (Exception e) {
    20. throw new BusinessException(ResError.SYS_427);
    21. }
    22. }

    日期转日期格式字符串

    • JDK8之前

    使用SimpleDateFormat进行转换,但是线程不安全。

    1. /**
    2. * 日期转日期格式字符串
    3. * @param date 日期
    4. * @param pattern 日期格式
    5. *
    6. * @return
    7. */
    8. public static String dateToStr(Date date, String pattern) {
    9. try {
    10. SimpleDateFormat dateTimeFormat = new SimpleDateFormat(pattern);
    11. return dateTimeFormat.format(date);
    12. } catch (Exception e) {
    13. throw new RuntimeException("parse date error");
    14. }
    15. }
    • JDK8之后
    1. /**
    2. * LocalDateTime转日期格式字符串 线程安全
    3. * @param date 日期
    4. * @param pattern 日期格式
    5. *
    6. * @return
    7. */
    8. public static String dateToStr8(LocalDateTime date, String pattern) {
    9. try {
    10. DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern(pattern);
    11. return dateFormat.format(date);
    12. } catch (Exception e) {
    13. throw new RuntimeException("parse date error");
    14. }
    15. }
    16. /**
    17. * 日期转日期格式字符串 线程安全
    18. * @param date 日期
    19. * @param pattern 日期格式
    20. *
    21. * @return
    22. */
    23. public static String dateToStr8(Date date, String pattern) {
    24. try {
    25. DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern(pattern);
    26. if ("yyyy-MM-dd".equals(pattern)) {
    27. LocalDate localDate = LocalDateTime
    28. .ofInstant(date.toInstant(),ZoneId.systemDefault())
    29. .toLocalDate();
    30. return dateFormat.format(localDate);
    31. } else {
    32. LocalDateTime localDateTime = LocalDateTime
    33. .ofInstant(date.toInstant(),ZoneId.systemDefault());
    34. return dateFormat.format(localDateTime);
    35. }
    36. } catch (Exception e) {
    37. throw new BusinessException(ResError.SYS_427);
    38. }
    39. }

    LocalDate、Date、String转换

    • Date与LocalDate/LocalDateTime互转
    1. // LocalDateTime转Date
    2. LocalDateTime localDateTime = LocalDateTime.now();
    3. Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    4. // LocalDate转Date
    5. LocalDate localDate = LocalDate.now();
    6. Date date = Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
    7. // Date转LocalDateTime
    8. Date date = new Date();
    9. LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(),ZoneId.systemDefault());
    10. // Date转LocalDate
    11. Date date = new Date();
    12. LocalDate localDate = LocalDateTime.ofInstant(date.toInstant(),ZoneId.systemDefault()).toLocalDate();
    • LocalDate/LocalDateTime与String互转
    1. // LocalDate转String
    2. LocalDate localDate = LocalDate.now();
    3. DateTimeFormatter dateTimeFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    4. String dateStr = localDate.format(dateTimeFormat);
    5. // LocalDateTime转String
    6. LocalDateTime localDateTime = LocalDateTime.now();
    7. DateTimeFormatter dateTimeFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    8. String dateStr = localDateTime.format(dateTimeFormat);
    9. // String转LocalDate
    10. String dateStr = "2022-11-07";
    11. DateTimeFormatter dateTimeFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    12. LocalDate localDate = LocalDate.parse(dateStr,dateTimeFormat);
    13. // String转LocalDateTime
    14. String dateStr = "2022-11-07 12:00:00";
    15. DateTimeFormatter dateTimeFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    16. LocalDateTime localDateTime = LocalDateTime.parse(dateStr,dateTimeFormat);

    时间加减

    • JDK8之前

    Jdk1.1 之后, 带来了java.util.Calendar工具类, 用于处理时间,格式为【Calendar.getInstance().add(int field, int amount)】;

    field为Calendar.DATE表示加减的是天,为Calendar.MONTH表示加减的是月,等;

    amount表示加减的日期数,正数表示日期加,负数表示日期减,如下:

    1. // 三天前
    2. Calendar calendar1 = Calendar.getInstance();
    3. calendar1.add(Calendar.DATE, -3);
    4. System.out.println(calendar1.getTime());
    5. // 三天后
    6. Calendar calendar2 = Calendar.getInstance();
    7. calendar2.add(Calendar.DATE, 3);
    8. System.out.println(calendar2.getTime());
    9. // 三分钟后
    10. Calendar calendar3 = Calendar.getInstance();
    11. calendar3.add(Calendar.MINUTE, 3);
    12. System.out.println(calendar3.getTime());
    13. // 三小时后
    14. Calendar calendar4 = Calendar.getInstance();
    15. calendar4.add(Calendar.HOUR, 3);
    16. System.out.println(calendar4.getTime());
    17. // 三月后
    18. Calendar calendar5 = Calendar.getInstance();
    19. calendar5.add(Calendar.MONTH, 3);
    20. System.out.println(calendar5.getTime());

    操作结果:

    1. Fri Nov 04 11:06:14 CST 2022
    2. Thu Nov 10 11:06:14 CST 2022
    3. Mon Nov 07 11:09:14 CST 2022
    4. Mon Nov 07 14:06:14 CST 2022
    5. Tue Feb 07 11:06:14 CST 2023
    • JDK8之后

    直接使用LocalDateTime自带的方法即可,如下所示

    1. DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    2. LocalDateTime now = LocalDateTime.now();
    3. System.out.println("当前时间:"+ now.format(format));
    4. LocalDateTime plusTime = now.plusMonths(1).plusDays(1).plusHours(1).plusMinutes(1).plusSeconds(1);
    5. System.out.println("增加1月1天1小时1分钟1秒时间后:" + plusTime.format(format));
    6. LocalDateTime minusTime = now.minusMonths(1).minusDays(1).minusHours(1).minusMinutes(1).minusSeconds(1);
    7. System.out.println("减去1月1天1小时1分钟1秒时间后:" + minusTime.format(format));

    操作结果:

    1. 当前时间:2022-11-07 11:14:26
    2. 增加111小时1分钟1秒时间后:2022-12-08 12:15:27
    3. 减去111小时1分钟1秒时间后:2022-10-06 10:13:25

    时间比较

    1. LocalDateTime now = LocalDateTime.now();
    2. LocalDateTime yesterday = now.minusDays(1);
    3. System.out.println(now + "在" + yesterday + "之后吗?" + now.isAfter(yesterday));
    4. System.out.println(now + "在" + yesterday + "之前吗?" + now.isBefore(yesterday));
    5. // 时间差
    6. long day = yesterday.until(now, ChronoUnit.DAYS);
    7. long month = yesterday.until(now, ChronoUnit.MONTHS);
    8. long hours = yesterday.until(now, ChronoUnit.HOURS);
    9. long minutes = yesterday.until(now, ChronoUnit.MINUTES);
    10. System.out.println("相差月份" + month);
    11. System.out.println("相差天数" + day);
    12. System.out.println("相差小时" + hours);
    13. System.out.println("相差分钟" + minutes);

    时间扩展方法

    • JDK8之前
    1. /**
    2. * 获取上周周一(第一天是周一)
    3. *
    4. * @return
    5. */
    6. public static Date getPreviousMonday() {
    7. Calendar cal = Calendar.getInstance();
    8. // 将每周第一天设为星期一,默认是星期天
    9. cal.setFirstDayOfWeek(Calendar.MONDAY);
    10. cal.add(Calendar.DATE, -1 * 7);
    11. cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
    12. cal.set(Calendar.HOUR_OF_DAY, 0);
    13. cal.set(Calendar.MINUTE, 0);
    14. cal.set(Calendar.SECOND, 0);
    15. cal.set(Calendar.MILLISECOND, 0);
    16. return cal.getTime();
    17. }
    18. /**
    19. * 获取上周周日(第一天是周一)
    20. * @return
    21. */
    22. public static Date getLastSunday() {
    23. Calendar cal = Calendar.getInstance();
    24. //将每周第一天设为星期一,默认是星期天
    25. cal.setFirstDayOfWeek(Calendar.MONDAY);
    26. cal.add(Calendar.DATE, -1*7);
    27. cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
    28. cal.set(Calendar.HOUR_OF_DAY, 0);
    29. cal.set(Calendar.MINUTE, 0);
    30. cal.set(Calendar.SECOND, 0);
    31. cal.set(Calendar.MILLISECOND, 0);
    32. return cal.getTime();
    33. }
    • JDK8之后
    1. LocalDateTime now = LocalDateTime.now();
    2. System.out.println("当前时间:" + now);
    3. // 当天最后一秒
    4. LocalDateTime lastSecondOfDay = now.withHour(23).withMinute(59).withSecond(59);
    5. System.out.println("当天最后一秒:" + lastSecondOfDay);
    6. // 本月第一天
    7. LocalDateTime firstDay = now.withDayOfMonth(1);
    8. System.out.println("本月第一天:" + firstDay);
    9. // 本月最后一天
    10. LocalDateTime lastDay = now.with(TemporalAdjusters.lastDayOfMonth());
    11. System.out.println("本月最后一天:" + lastDay);
    12. // 今日所在周的周一
    13. LocalDateTime monday = now.with(TemporalAdjusters.previous(DayOfWeek.SUNDAY)).plusDays(1).withHour(0).withMinute(0).withSecond(0);
    14. System.out.println("今日所在周的周一:" + monday);
    15. // 今日所在周的周二
    16. LocalDateTime tuesday = now.with(TemporalAdjusters.previous(DayOfWeek.SUNDAY)).plusDays(2).withHour(0).withMinute(0).withSecond(0);
    17. System.out.println("今日所在周的周二:" + tuesday);
    18. // 今日所在周的周日
    19. LocalDateTime sunday = now.with(TemporalAdjusters.next(DayOfWeek.MONDAY)).minusDays(1).withHour(23).withMinute(59).withSecond(59);
    20. System.out.println("今日所在周的周日:" + sunday);
    21. // 今日所在周的上周一
    22. LocalDateTime lastMonday = now.with(TemporalAdjusters.previous(DayOfWeek.MONDAY));
    23. System.out.println("今日所在周的上周一:" + lastMonday);
    24. // 是否闰年
    25. System.out.println("今年是否闰年:" + Year.isLeap(now.getYear()));

    操作结果:

    1. 当前时间:2022-11-07T11:40:20.377
    2. 当天最后一秒:2022-11-07T23:59:59.377
    3. 本月第一天:2022-11-01T11:40:20.377
    4. 本月最后一天:2022-11-30T11:40:20.377
    5. 今日所在周的周一:2022-11-07T00:00:00.377
    6. 今日所在周的周二:2022-11-08T00:00:00.377
    7. 今日所在周的周日:2022-11-13T23:59:59.377
    8. 今日所在周的上周一:2022-10-31T11:40:20.377
    9. 今年是否闰年:false

    获取上/下一个分钟值以0或者5结尾的时间点

    1. /**
    2. * 获取下一个分钟值以0或者5结尾的时间点(单位:毫秒)
    3. * @return
    4. */
    5. public static long getNextMillisEndWithMinute0or5(Date baseTime) {
    6. Calendar calendar = Calendar.getInstance();
    7. calendar.setTime(baseTime);
    8. int minute = calendar.get(Calendar.MINUTE);
    9. if (minute < 55) {
    10. int add = minute%10 < 5? 5 - minute%10 : 10 - minute%10;
    11. calendar.add(Calendar.MINUTE,add);
    12. calendar.set(Calendar.SECOND, 0);
    13. calendar.set(Calendar.MILLISECOND, 0);
    14. return calendar.getTime().getTime();
    15. }
    16. calendar.set(Calendar.MINUTE, 0);
    17. calendar.set(Calendar.SECOND, 0);
    18. calendar.set(Calendar.MILLISECOND, 0);
    19. Date endTime = DateUtils.addHours(calendar.getTime(), 1);
    20. return endTime.getTime();
    21. }
    22. /**
    23. * 获取上一个分钟值以0或者5结尾的时间点(单位:毫秒)
    24. * @return
    25. */
    26. public static long getLastMillisEndWithMinute0or5(Date baseTime) {
    27. Calendar calendar = Calendar.getInstance();
    28. calendar.setTime(baseTime);
    29. int minute = calendar.get(Calendar.MINUTE);
    30. if (minute < 55) {
    31. int add = minute%10 < 5? 5 - minute%10 : 10 - minute%10;
    32. calendar.add(Calendar.MINUTE, -(5-add));
    33. calendar.set(Calendar.SECOND, 0);
    34. calendar.set(Calendar.MILLISECOND, 0);
    35. return calendar.getTime().getTime();
    36. }
    37. calendar.set(Calendar.MINUTE, 0);
    38. calendar.set(Calendar.SECOND, 0);
    39. calendar.set(Calendar.MILLISECOND, 0);
    40. Date endTime = DateUtils.addHours(calendar.getTime(), 1);
    41. return endTime.getTime();
    42. }
    43. public static String getNextStrTimeEndWithMinute0or5(Date date, String format) {
    44. if(StringUtil.isEmpty(format)){
    45. format = "yyyy-MM-dd HH:mm:ss";
    46. }
    47. return DateFormatUtils.format(getNextMillisEndWithMinute0or5(date),format);
    48. }
    49. public static String getLastStrTimeEndWithMinute0or5(Date date, String format) {
    50. if(StringUtil.isEmpty(format)){
    51. format = "yyyy-MM-dd HH:mm:ss";
    52. }
    53. return DateFormatUtils.format(getLastMillisEndWithMinute0or5(date),format);
    54. }

  • 相关阅读:
    HTML进阶(5)- 其他元素
    秘密共享方案介绍SS
    Perl语言入门学习
    PCL 使用克拉默法则进行三点定圆(二维)
    nodejs基于微信小程序的书籍销售系统--计算机毕业设计
    如何获得jd商品分类API数据
    使用 TensorFlow.js 在浏览器中进行自定义对象检测
    剪辑视频时PR播放卡顿不连贯|如何修复Premiere软件中播放太卡问题
    基于轻量级卷积神经网络CNN开发构建打架斗殴识别分析系统
    软考系统架构师常考知识点整理(含案例分析、论文历年题目总结)
  • 原文地址:https://blog.csdn.net/qq_37634156/article/details/127630033