java8的时间处理

    科技2025-07-30  21

    时间是开发过程中必不可少的,相信java8的时间api没出来之前,你们都用过SimpleDateFormat和Calendar,其中的痛苦我不必说,懂得都懂。还好,java8出了新的时间api,并且线程安全,性能更好,代码更加简洁。

    Calendar操作

    2.LocalDate:处理年,月,日

    获取当前日期 LocalDate now = LocalDate.now(); //2020-10-05 设置日期 LocalDate of = LocalDate.of(2020, 10, 5); //2020-10-05 获取年 // 2020 int year = now.getYear(); int i = now.get(ChronoField.YEAR); 获取月 Month month = now.getMonth(); //OCTOBER int i1 = now.get(ChronoField.MONTH_OF_YEAR); //10 获取日 int dayOfMonth = now.getDayOfMonth(); //5 int i2 = now.get(ChronoField.DAY_OF_MONTH); //5 获取星期 DayOfWeek dayOfWeek = now.getDayOfWeek(); //MONDAY int i3 = now.get(ChronoField.DAY_OF_WEEK); //1 日期计算 //增加1个月 LocalDate localDate = now.plusMonths(1); // 2020-11-05 //减少1个月 LocalDate minus = now.minus(1, ChronoUnit.MONTHS);// 2020-09-05 //修改年份 LocalDate localDate1 = now.withYear(2021); //2021-09-05 //当年多少天 int i4 = now.lengthOfYear(); //366 //当月多少天 int i5 = now.lengthOfMonth(); //当前日期是否在之后 false boolean after = now.isAfter(LocalDate.of(2020, 10, 10)); //当前日期是否在之前 true boolean before = now.isBefore(LocalDate.of(2020, 10, 10)); //当前日期是否相等 false boolean equalqual = now.isEqual(LocalDate.of(2020, 10, 10)); 日期格式化 LocalDate parse = LocalDate.parse("2020-10-28"); LocalDate parse1 = LocalDate.parse("2020-10-28", DateTimeFormatter.ISO_LOCAL_DATE); //2020-10-28

    3.LocalTime:处理时,分,秒

    当前时间 LocalTime localTime = LocalTime.now();//16:43:40.157 设置时间 LocalTime of1 = LocalTime.of(12, 30);//12:30 LocalTime 这里只介绍这个api,其实和LocaDate 的api差不多,大家可以自己去尝试下,这里我就贴一下这两者的api,可以对比下。

     

    LocalDate和LocalTime对比-1

    LocalDate和LocalTime对比-2

    4.LocalDateTime:处理年,月,日,时,分,秒

    虽然LocalDateTime的api跟上面介绍的2个时间类也有很多相似,不过这里还是说一说。

    当前日期时间 LocalDateTime now1 = LocalDateTime.now();//2020-10-05T13:02:22.223 设置时间 //2020-10-05T7:05:36.209 LocalDateTime of2 = LocalDateTime.of(LocalDate.now(), LocalTime.now());

     

    LocalDateTime

    可以看到至少有6个方法可以设置日期时间,但打印出来的格式却不是我们想要的。这时就需要一个格式化对象了---DateTimeFormatter。

    5.DateTimeFormatter

    这个类允许你使用默认的格式或者自定义格式(但必须合理)。我们来看几个例子

    自定义格式 LocalDateTime now1 = LocalDateTime.now(); DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss,年月日之间是-yyyy/MM/dd HH:mm:ss"); String format = now1.format(dateTimeFormatter);//2020/10/05 7:14:14 //注意此时dateTimeFormatter 格式为yyyy-MM-dd HH:mm:ss,年月日之间是-LocalDate localDate3 = LocalDate.parse("2020-12-07 07:43:53",dateTimeFormatter);//2020-12-07 默认格式 LocalDateTime now1 = LocalDateTime.now(); System.out.println(now1.format(DateTimeFormatter.BASIC_ISO_DATE));//20201005 System.out.println(now1.format(DateTimeFormatter.ISO_DATE_TIME));//2020-10-05T7:25:35.325 System.out.println(now1.format(DateTimeFormatter.ISO_LOCAL_DATE));//2020-10-05 System.out.println(now1.format(DateTimeFormatter.ISO_LOCAL_TIME));//7:26:52.528

     

    DateTimeFormatter默认格式

    格式化的方法有很多,还需要根据实际的业务需要来灵活运用,以上只是简单的例举了几个例子。大家还需自行去尝试敲代码,加深印象。

    Processed: 0.014, SQL: 8