java获取当前时间的方法:LocalDateTime、Date、Calendar,以及三者的比较


前言


在开发时我们经常需要获取当前时间或者对时间进项处理(在某个时间的基础上增加或者减少),java获取时间的方法比较多,有LocalDateTime、Date、Calendar等,其中LocalDateTime是java8的新特性,相比较其它两个而言,LocalDateTime有很多优势,这也是最推荐使用的方法。
下面我们先来介绍一个LocalDateTime的用法,然后介绍Date、Calendar的用法,最后比较它们的区别。

一、LocalDateTime

JDK1.8版本中新引入的API,加强了对时间的管理,有很多特别好用的时间运算方法,而且是线程安全的。

1.1 获取当前时间LocalDate.now()

    @Test
    void test() {
    
    
        LocalDate localDate = LocalDate.now();
        LocalTime localTime = LocalTime.now();
        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println("localDate:"+localDate);//2023-02-22
        System.out.println("localTime:"+localTime);//17:25:36.590
        System.out.println("localDateTime:"+localDateTime);//2023-02-22T17:25:36.590
    }

输出结果:
在这里插入图片描述
可以看到不用做格式转换就可以得到可读性很高的日期格式。
注意:ISO 8601规定的日期和时间分隔符是T。标准格式如下:

日期:yyyy-MM-dd
时间:HH:mm:ss
带毫秒的时间:HH:mm:ss.SSS
日期和时间:yyyy-MM-dd'T'HH:mm:ss
带毫秒的日期和时间:yyyy-MM-dd'T'HH:mm:ss.SSS

1.2 获取当前时间的年、月、日、时分秒localDateTime.getYear()……

    @Test
    void test() {
    
    
        LocalDateTime localDateTime = LocalDateTime.now(); // 获取当前时间
        int year = localDateTime.getYear(); // 获取年份 2023
        int month = localDateTime.getMonthValue(); // 获取月份 2
        int day = localDateTime.getDayOfMonth(); // 获取月中的天数 22
        int hour = localDateTime.getHour(); // 获取当前的小时 17
        int minute = localDateTime.getMinute(); // 获取当前分钟 33
        int second = localDateTime.getSecond(); // 获取当前秒数 22
        System.out.println(year);
        System.out.println(month);
        System.out.println(day);
        System.out.println(hour);
        System.out.println(minute);
        System.out.println(second);
    }

输出结果:
在这里插入图片描述

1.3 给LocalDateTime赋值LocalDateTime.of()

    void test() {
    
    
        LocalDateTime of = LocalDateTime.of(2023,2,22,22,22,22);
        System.out.println(of); // 输出2023-02-22T22:22:22
    }

输出结果:
在这里插入图片描述

1.4 时间与字符串相互转换LocalDateTime.parse()

    @Test
    void test() {
    
    
        // 将字符串转换为指定格式的时间(格式要和给定的格式一致,不然会报错)
        LocalDateTime parse = LocalDateTime.parse("2023-02-22 22:22:22", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        LocalDateTime parse1 = LocalDateTime.parse("2023 02 22 22:22:22", DateTimeFormatter.ofPattern("yyyy MM dd HH:mm:ss"));
        LocalDateTime parse2 = LocalDateTime.parse("2023.02.22 22:22:22", DateTimeFormatter.ofPattern("yyyy.MM.dd HH:mm:ss"));
        System.out.println(parse); // 输出2023-02-22T22:22:22
        System.out.println(parse1); // 输出2023-02-22T22:22:22
        System.out.println(parse2); // 输出2023-02-22T22:22:22
        // 时间转字符串
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter of = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String dateTime = now.format(of);
        System.out.println(dateTime); // 输出 2023-02-22 17:56:18
    }

输出结果:
在这里插入图片描述

1.5 时间运算——加上对应时间LocalDateTime.now().plusYears(2)

LocalDateTime提供了对日期和时间进行加减的非常简单的链式调用,让时间运算变得非常简单:

    @Test
    void test() {
    
    
        LocalDateTime now = LocalDateTime.now(); // 当前时间2023-02-22T18:00:19.352
        LocalDateTime plusYears= now.plusYears(2); // 在当前时间加上2年2025-02-22T18:00:19.352
        LocalDateTime plusMonths= now.plusMonths(2);// 在当前时间商加上2月2023-04-22T18:00:19.352
        LocalDateTime plusDays= now.plusDays(2); // 在当前时间加上2天2023-02-24T18:00:19.352
        LocalDateTime plusHours= now.plusHours(2); // 在当前时间加上2个小时2023-02-22T20:00:19.352
        LocalDateTime plusMinutes= now.plusMinutes(30); // 在当前时间加上30分钟2023-02-22T18:30:19.352
        LocalDateTime plusSeconds = now.plusSeconds(30); // 在当前时间加上30秒2023-02-22T18:00:49.352
        System.out.println(now);
        System.out.println(plusYears);
        System.out.println(plusMonths);
        System.out.println(plusDays);
        System.out.println(plusHours);
        System.out.println(plusMinutes);
        System.out.println(plusSeconds);
    }

输出结果:
在这里插入图片描述

1.6 时间运算——减去对应时间LocalDateTime.now().minusYears(2)

    @Test
    void test() {
    
    
        LocalDateTime now = LocalDateTime.now(); // 当前时间
        LocalDateTime minusYears = now.minusYears(2); // 在当前时间减上2年
        LocalDateTime minusMonths = now.minusMonths(2);// 在当前时间商减上2月
        LocalDateTime minusDays = now.minusDays(2); // 在当前时间减上2天
        LocalDateTime minusHours = now.minusHours(2); // 在当前时间减上2个小时
        LocalDateTime minusMinutes = now.minusMinutes(30); // 在当前时间减上30分钟
        LocalDateTime minusSeconds = now.minusSeconds(30); // 在当前时间减上30秒
        System.out.println("now:" + now);
        System.out.println("minusYears:" + minusYears);
        System.out.println("minusMonths:" + minusMonths);
        System.out.println("minusDays:" + minusDays);
        System.out.println("minusHours:" + minusHours);
        System.out.println("minusMinutes:" + minusMinutes);
        System.out.println("minusSeconds:" + minusSeconds);
    }

输出结果:
在这里插入图片描述

1.7 两个时间比较LocalDateTime.now().compareTo()

    @Test
    void test() {
    
    
        LocalDateTime now = LocalDateTime.now(); // 当前时间
        LocalDateTime now1 = now.plusYears(5); // 在当前时间加上5年
        //  给LocalDateTime 赋值
        LocalDateTime of = LocalDateTime.of(2023,2,2,22,22,22);
        LocalDateTime of1 = LocalDateTime.of(2023,8,5,1,1,1);
        //两个时间作比较,第一个时间减去第二个时间(如果年份相同,比较月份,月份相同比较天数,以此类推)
        int compareTo = now1.compareTo(now);
        int compareTo1 = now.compareTo(now1);
        int compareTo2 = now.compareTo(of);
        int compareTo3 = now.compareTo(of1);
        System.out.println(now);   // 输出 2023-02-22T20:19:44.112v
        System.out.println(now1); // 输出 2028-02-22T20:19:44.112
        System.out.println(of); // 输出 2023-02-02T22:22:22
        System.out.println(of1); // 输出 2023-08-05T01:01:01
        System.out.println(compareTo); // 输出 5
        System.out.println(compareTo1); // 输出 -5
        System.out.println(compareTo2); // 输出 20
        System.out.println(compareTo3); // 输出 -6
    }

输出结果:

1.8 利用Duration计算时间差Duration.between(of,now).toMillis()

注意没有计算相差的年和秒值,对于要计算相差的秒数,可以利用计算毫秒来进行转换。

    @Test
    void test() {
    
    
        LocalDateTime now = LocalDateTime.now(); // 当前时间
        //  给LocalDateTime 赋值
        LocalDateTime of = LocalDateTime.of(2022,2,22,2,2,2);
        Duration duration = Duration.between(of,now); // 后面减去前面
        long toDays = Duration.between(of,now).toDays(); //相差的天数
        long toHours = Duration.between(of,now).toHours();//相差的小时数
        long toMinutes = Duration.between(of,now).toMinutes();//相差的分钟数
        long toMillis = Duration.between(of,now).toMillis();//相差毫秒数
        long toNanos = Duration.between(of,now).toNanos();//相差的纳秒数
        System.out.println("toDays:"+ toDays); // 输出 toDays:365
        System.out.println("toHours:"+ toHours); // 输出 toHours:8778
        System.out.println("toMinutes:"+ toMinutes); // 输出 toMinutes:526732
        System.out.println("toMillis:"+ toMillis); // 输出 toMillis:31603973840
        System.out.println("toNanos:"+ toNanos); // 输出 toNanos:31603973840000000
    }

输出结果:
在这里插入图片描述

1.9 改变当前时间的年、月、日、时、分、秒LocalDateTime.now().withYear(2060)

    @Test
    void test() {
    
    
        LocalDateTime now = LocalDateTime.now(); // 当前时间
        LocalDateTime withYear = now.withYear(2060); // 改变当前年份(变成2060年)
        LocalDateTime withMonth = now.withMonth(12); // 改变当前月份(变成12月份)
        LocalDateTime withDayOfMonth = now.withDayOfMonth(28); //改变当前天数(变成28日)
        LocalDateTime withHour = now.withHour(23); // 改变当前小时数(变成23时)
        LocalDateTime withMinute = now.withMinute(30); // 改变当前分钟(变成30分钟)
        LocalDateTime withSecond = now.withSecond(23); // 改变当前小时数(变成23时)
        LocalDateTime withDayOfYear = now.withDayOfYear(60); // 从一月一号开始加上60天
        System.out.println(now);
        System.out.println("withYear:"+ withYear);
        System.out.println("withMonth:"+ withMonth);
        System.out.println("withDayOfMonth:"+ withDayOfMonth);
        System.out.println("withHour:"+ withHour);
        System.out.println("withMinute:"+ withMinute);
        System.out.println("withSecond:"+ withSecond);
        System.out.println("withDayOfYear:"+ withDayOfYear);
    }

输出结果:
在这里插入图片描述

1.10 自定义输出的格式DateTimeFormatter.ofPattern(“yyyy/MM/dd HH:mm:ss”);

    @Test
    void test() {
    
    
        // 自定义格式化:
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
        DateTimeFormatter dtf1 = DateTimeFormatter.ofPattern("yyyy.MM.dd HH:mm:ss");
        System.out.println("自定义格式yyyy/MM/dd HH:mm:ss :"+dtf.format(LocalDateTime.now()));
        System.out.println("自定义格式yyyy.MM.dd HH:mm:ss :"+dtf1.format(LocalDateTime.now()));

        // 用自定义格式解析:
        LocalDateTime dt2 = LocalDateTime.parse("2020/10/20 15:16:17", dtf);
        System.out.println("格式解析:"+dt2);
    }

输出结果:
在这里插入图片描述

1.11 LocalDateTime的with()方法

// 本月第一天0:00时刻:
LocalDateTime firstDay = LocalDate.now().withDayOfMonth(1).atStartOfDay();
// 本月最后1天:
LocalDate lastDay = LocalDate.now().with(TemporalAdjusters.lastDayOfMonth());
// 下月第1天:
LocalDate nextMonthFirstDay = LocalDate.now().with(TemporalAdjusters.firstDayOfNextMonth());
// 本月第1个周一:
LocalDate firstWeekday = LocalDate.now().with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY));

输出结果:

1.12 两个日期前后的比较与判断LocalDateTime.now().isBefore()

    @Test
    void test() {
    
    
        //判断两个时间点的前后
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime target = LocalDateTime.of(2022, 2, 22, 22, 22, 22);
        boolean isBefore = now.isBefore(target);
        System.out.println("now:"+now);
        System.out.println("target:"+target);
        System.out.println("isBefore:"+isBefore);
        System.out.println(LocalDate.now().isBefore(LocalDate.of(2022, 2, 22)));
        System.out.println(LocalTime.now().isAfter(LocalTime.parse("08:15:00")));
    }
    }

输出结果:
在这里插入图片描述

二、Util获取当前时间

2.1 Date

2.1.1 Date获取当前时间

    @Test
    void test() {
    
    
        Date date = new Date(); // 返回当前时间戳格式
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 改变格式
        System.out.println(dateFormat.format(date)); // 获取当前时间  2023-02-22 21:24:53
    }

2.1.1 Date存在的缺陷

如果不格式化,打印出的日期可读性差:

    @Test
    void test() {
    
    
        Date date = new Date(); // 返回当前时间戳格式
        System.out.println(date); // 获取当前时间  Wed Feb 22 21:34:18 CST 2023
    }

通常会使用SimpleDateFormate来实现格式化,但是sdf最大的问题是线程不安全的。

2.2 Calendar

    @Test
    void test() {
    
    
        Calendar cal= Calendar.getInstance(); // 返回当前时间戳格式
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 改变格式
        System.out.println(dateFormat.format(cal.getTime())); // 获取当前时间
        int y=cal.get(Calendar.YEAR); // 获取当前年份
        int m=cal.get(Calendar.MONTH); // 获取当前月份
        int d=cal.get(Calendar.DATE); // 获取当前日期
        int h=cal.get(Calendar.HOUR_OF_DAY); // 获取当前小时
        int mi=cal.get(Calendar.MINUTE); // 获取当前分钟
        int s=cal.get(Calendar.SECOND); // 获取当前秒数
        System.out.println("现在时刻是"+y+"年"+m+"月"+d+"日"+h+"时"+mi+"分"+s+"秒");
    }

三、System.currentTimeMillis()

SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z"); // 改变格式
Date date = new Date(System.currentTimeMillis()); // 返回当前时间戳格式
System.out.println(formatter.format(date)); // 获取当前时间


总结

LocalDateTime获取时间以及计算都非常方便,而且是线程安全的,简易使用LocalDateTime。

猜你喜欢

转载自blog.csdn.net/sunzixiao/article/details/129166030