详解JDK8中新的日期时间工具类,真的很好用

1.旧版日期时间的问题

  在旧版本中JDK对于日期和时间这块的时间是非常差的。

    /**
     * 旧版日期时间设计的问题
     */
    @Test
    public void test01() throws Exception{
        // 1.设计不合理
        Date date = new Date(2021,05,05);
        System.out.println(date);

        // 2.时间格式化和解析操作是线程不安全的
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < 50; i++) {
            new Thread(()->{
               // System.out.println(sdf.format(date));
                try {
                    System.out.println(sdf.parse("2021-05-06"));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }

      1、设计不合理,在java.util和java.sql的包中都有日期类,java.util.Date同时包含日期和时间的,而java.sql.Date仅仅包含日期,此外用于格式化和解析的类在java.text包下。
        2、非线程安全,java.util.Date是非线程安全的,所有的日期类都是可变的,这是java日期类最大的问题之一。
        3、时区处理麻烦,日期类并不提供国际化,没有时区支持。

2. 新日期时间API介绍

        JDK 8中增加了一套全新的日期时间API,这套API设计合理,是线程安全的。新的日期及时间API位于 java.time 包
中,下面是一些关键类。

LocalDate :表示日期,包含年月日,格式为 2019-10-16
LocalTime :表示时间,包含时分秒,格式为 16:38:54.158549300
LocalDateTime :表示日期时间,包含年月日,时分秒,格式为 2018-09-06T15:33:56.750
DateTimeFormatter :日期时间格式化类。
Instant:时间戳,表示一个特定的时间瞬间。
Duration:用于计算2个时间(LocalTime,时分秒)的距离
Period:用于计算2个日期(LocalDate,年月日)的距离
ZonedDateTime :包含时区的时间
  

Java中使用的历法是ISO 8601日历系统,它是世界民用历法,也就是我们所说的公历。平年有365天,闰年是366
天。此外Java 8还提供了4套其他历法,分别是:

ThaiBuddhistDate:泰国佛教历
MinguoDate:中华民国历
JapaneseDate:日本历
HijrahDate:伊斯兰历

3.LocalDate常用基础操作

    @Test
    public void test01(){
        // 1.创建指定的日期
        LocalDate date1 = LocalDate.of(2021, 05, 06);
        System.out.println("指定日期 = "+date1);

        // 2.得到当前的日期
        LocalDate now = LocalDate.now();
        System.out.println("当前日期 = "+now);

        // 3.根据LocalDate对象获取对应的日期信息
        System.out.println("年:" + now.getYear());
        System.out.println("月:" + now.getMonth().getValue());
        System.out.println("日:" + now.getDayOfMonth());
        System.out.println("星期:" + now.getDayOfWeek().getValue());
    }

4.LocalTime常用基础操作

    @Test
    public void test02(){

        // 1.得到指定的时间
        LocalTime time = LocalTime.of(5,26,33,23145);
        System.out.println("指定时间->" + time);

        // 2.获取当前的时间
        LocalTime now = LocalTime.now();
        System.out.println("当前时间->" + now);

        // 3.获取时间信息
        System.out.println("获取当前小时->" + now.getHour());
        System.out.println("获取当前分钟->" + now.getMinute());
        System.out.println("获取当前秒中->" + now.getSecond());
        System.out.println("获取当前毫秒->" + now.getNano());
    }

5.LocalDateTime日期和时间类型常用基础操作

LocalDateTime参数:

year:表示的年份,从MIN_YEAR到MAX_YEAR

month:表示月份

dayOfMonth:表示日期,从1到31

hour:表示小时,从0到23

minute:表示分钟,从0到59

second:表示从0到59的秒钟

nanoOfSecond:表示纳秒,从0到999,999,999

 @Test
    public void test03(){
        // 获取指定的日期时间
        LocalDateTime dateTime =
                LocalDateTime.of(2020
                        , 06
                        , 01
                        , 12
                        , 12
                        , 33
                        , 213);
        System.out.println("获取指定日期时间->" + dateTime);
        // 获取当前的日期时间
        LocalDateTime now = LocalDateTime.now();
        System.out.println("获取当前日期时间->" + now);
        // 获取日期时间信息
        System.out.println("获取年份->" + now.getYear());
        System.out.println("获取月份->" + now.getMonth().getValue());
        System.out.println("获取日->" + now.getDayOfMonth());
        System.out.println("获取星期几->" + now.getDayOfWeek().getValue());
        System.out.println("获取小时->" + now.getHour());
        System.out.println("获取分钟->" + now.getMinute());
        System.out.println("获取秒钟->" + now.getSecond());
        System.out.println("获取毫秒->" + now.getNano());
    }

6.日期时间的修改

   @Test
    public void test01(){
        LocalDateTime now = LocalDateTime.now();
        System.out.println("now = "+now);
        // 修改日期时间  对日期时间的修改,对已存在的LocalDate对象,创建了它模板
        // 并不会修改原来的信息
        LocalDateTime localDateTime = now.withYear(1998);
        System.out.println("now :"+now);
        System.out.println("修改后的:" + localDateTime);

        System.out.println("月份:" + now.withMonth(10));
        System.out.println("天:" + now.withDayOfMonth(6));
        System.out.println("小时:" + now.withHour(8));
        System.out.println("分钟:" + now.withMinute(15));

        // 在当前日期时间的基础上 加上或者减去指定的时间
        System.out.println("两天后:" + now.plusDays(2));
        System.out.println("10年后:"+now.plusYears(10));
        System.out.println("6个月后 = " + now.plusMonths(6));

        System.out.println("10年前 = " + now.minusYears(10));
        System.out.println("半年前 = " + now.minusMonths(6));
        System.out.println("一周前 = " + now.minusDays(7));
    }

7.日期时间的比较

在JDK8中要实现 日期的比较 isAfter  isBefore isEqual 通过这几个方法来直接比较

  @Test
    public void test02(){
        LocalDate now = LocalDate.now();
        LocalDate date = LocalDate.of(2022, 1, 1);
       
        System.out.println(now.isAfter(date)); // false
        System.out.println(now.isBefore(date)); // true
        System.out.println(now.isEqual(date)); // false
    }

8.格式化和解析操作

  /**
     * 日期格式化
     */
    @Test
    public void test01(){
        LocalDateTime now = LocalDateTime.now();
        // 指定格式  使用系统默认的格式 2021-05-27T16:16:38.139
        DateTimeFormatter isoLocalDateTime = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        // 将日期时间转换为字符串
        String format = now.format(isoLocalDateTime);
        System.out.println("format = " + format);

        // 通过 ofPattern 方法来指定特定的格式
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String format1 = now.format(dateTimeFormatter);
        // 2021-05-27 16:16:38
        System.out.println("format1 = " + format1);

        // 将字符串解析为一个 日期时间类型
        LocalDateTime parse = LocalDateTime.parse("1997-05-06 22:45:16", dateTimeFormatter);
        // parse = 1997-05-06T22:45:16
        System.out.println("parse = " + parse);
    }

9.计算日期时间差

  1. Duration:用来计算两个时间差(LocalTime)
  2. Period:用来计算两个日期差(LocalDate)
@Test
    public void test01(){
        // 计算时间差
        LocalTime now = LocalTime.now();
        LocalTime time = LocalTime.of(22, 48, 59);
        System.out.println("now = " + now);
        // 通过Duration来计算时间差
        Duration duration = Duration.between(now, time);
        System.out.println(duration.toDays()); // 0
        System.out.println(duration.toHours()); // 6
        System.out.println(duration.toMinutes()); // 368
        System.out.println(duration.toMillis()); // 22124240

        // 计算日期差
        LocalDate nowDate = LocalDate.now();
        LocalDate date = LocalDate.of(1997, 12, 5);
        Period period = Period.between(date, nowDate);
        System.out.println(period.getYears()); // 23
        System.out.println(period.getMonths()); // 5
        System.out.println(period.getDays()); // 22
    }

10. 时间校正器

             方法                                                            描述
dayOfWeekInMonth                             返回同一个月中每周的第几天
firstDayOfMonth                                             返回当月的第一天
firstDayOfNextMonth                                  返回下月的第一天
firstDayOfNextYear                                     返回下一年的第一天
firstDayOfYear                                             返回本年的第一天
firstInMonth                                                     返回同一个月中第一个星期几
lastDayOfMonth                                             返回当月的最后一天
lastDayOfNextMonth                                     返回下月的最后一天
lastDayOfNextYear                                     返回下一年的最后一天
lastDayOfYear                                             返回本年的最后一天
lastInMonth                                             返回同一个月中最后一个星期几
next / previous                                     返回后一个/前一个给定的星期几
nextOrSame / previousOrSame          返回后一个/前一个给定的星期几,如果这个值满足条件,直接返回

LocalDateTime now = LocalDateTime.now();
System.out.println("当前时间:" + now + "======>" + now.getDayOfWeek());
System.out.println("下一个周一:" + now.with(TemporalAdjusters.next(DayOfWeek.MONDAY)));
System.out.println("上一个周一:" + now.with(TemporalAdjusters.previous(DayOfWeek.MONDAY)));
System.out.println("下一个周五:" + now.with(TemporalAdjusters.nextOrSame(DayOfWeek.FRIDAY)));
System.out.println("上一个周五:" + now.with(TemporalAdjusters.previousOrSame(DayOfWeek.FRIDAY)));
System.out.println("本月最后一个周五:" + now.with(TemporalAdjusters.lastInMonth(DayOfWeek.FRIDAY)));
System.out.println("本月第一个周五:" + now.with(TemporalAdjusters.firstInMonth(DayOfWeek.FRIDAY)));
System.out.println("本月第一天:" + now.with(TemporalAdjusters.firstDayOfMonth()));
System.out.println("本月最后一天:" + now.with(TemporalAdjusters.lastDayOfMonth()));
System.out.println("下月的第一天:" + now.with(TemporalAdjusters.firstDayOfNextMonth()));
System.out.println("今年的第一天:" + now.with(TemporalAdjusters.firstDayOfYear()));
System.out.println("今年的最后一天:" + now.with(TemporalAdjusters.lastDayOfYear()));
System.out.println("下一年的第一天:" + now.with(TemporalAdjusters.firstDayOfNextYear()));
System.out.println("本月的第二个周五:" + now.with(TemporalAdjusters.dayOfWeekInMonth(2,DayOfWeek.FRIDAY)));
System.out.println("两周后:" + now.with(TemporalAdjusters.ofDateAdjuster(date -> date.plusWeeks(2))));
/*打印结果:
当前时间:2020-04-03T11:32:59.871======>FRIDAY
下一个周一:2020-04-06T11:32:59.871
上一个周一:2020-03-30T11:32:59.871
下一个周五:2020-04-03T11:32:59.871
上一个周五:2020-04-03T11:32:59.871
本月最后一个周五:2020-04-24T11:32:59.871
本月第一个周五:2020-04-03T11:32:59.871
本月第一天:2020-04-01T11:32:59.871
本月最后一天:2020-04-30T11:32:59.871
下月的第一天:2020-05-01T11:32:59.871
今年的第一天:2020-01-01T11:32:59.871
今年的最后一天:2020-12-31T11:32:59.871
下一年的第一天:2021-01-01T11:32:59.871
本月的第二个周五:2020-04-10T11:32:59.871
两周后:2020-04-17T11:32:59.871
*/

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
JDK 8引入了新的时间日期类,用于处理日期时间的操作。其中包括了`LocalDate`、`LocalTime`、`LocalDateTime`、`Instant`、`Duration`和`Period`等类。 `LocalDate`类表示一个日期,可以用来表示年月日信息。你可以使用`of`方法来创建一个指定日期的`LocalDate`对象,例如`LocalDate.parse("2019-03-04", fmt)`可以创建一个表示2019年3月4日的`LocalDate`对象。你也可以使用`plusDays`方法来计算指定日期之后的日期。 `LocalTime`类表示一个时间,可以用来表示时分秒信息。可以使用`of`方法来创建一个指定时间的`LocalTime`对象。 `LocalDateTime`类表示一个日期时间的组合,可以用来表示年月日时分秒信息。你可以使用`of`方法来创建一个指定日期时间的`LocalDateTime`对象。 `Instant`类表示一个时刻,可以用来表示从1970年1月1日UTC时间开始的纳秒数。可以使用`now`方法来获取当前的`Instant`对象。 `Duration`类表示一个时间段,可以用来表示以秒和纳秒为单位的时间差。你可以使用`between`方法来计算两个时间之间的差距。 `Period`类表示一个日期段,可以用来表示年、月、日之间的差距。你可以使用`between`方法来计算两个日期之间的差距。 需要注意的是,`Period`类无法直接计算隔月的差距,而是只能计算日期的差距。如果需要计算隔月的差距,可以使用`toEpochDay`方法将日期转换为自1970年1月1日以来的天数,然后进行计算。 例如,通过`LocalDate.now()`可以获取当前时间,通过`plusDays`方法可以计算当前时间之后100天的日期,而通过`Period.between`方法可以计算两个日期之间的差距并获取天数。 请注意,在上述代码中,`DateTimeFormatter`类用于指定日期的格式化和解析。 中的代码可以计算两个日期之间的差距,并将结果以年、月、日的形式输出。 中的代码展示了如何计算隔月的差距,通过`toEpochDay`方法获取两个日期之间的天数差。 总结来说,JDK 8时间日期类提供了许多强大的功能,可以方便地进行日期时间的操作和计算。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

喝汽水的猫^

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值