How to get the current time in java: LocalDateTime, Date, Calendar, and the comparison of the three


foreword


During development, we often need to obtain the current time or process the time (increase or decrease based on a certain time). There are many ways to obtain time in java, including LocalDateTime, Date, Calendar, etc. LocalDateTime is a new feature of java8 , Compared with the other two, LocalDateTime has many advantages, which is also the most recommended method.
Let's first introduce the usage of a LocalDateTime, then introduce the usage of Date and Calendar, and finally compare their differences.

1. LocalDateTime

The newly introduced API in JDK1.8 version strengthens the management of time, has many particularly useful time calculation methods, and is thread-safe.

1.1 Get the current time 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
    }

Output result:
insert image description here
You can see that a highly readable date format can be obtained without format conversion.
Note: The date and time separator specified by ISO 8601 is T. The standard format is as follows:

日期: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 Get the year, month, day, hour, minute, and second of the current time 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);
    }

Output result:
insert image description here

1.3 Assign LocalDateTime to LocalDateTime.of()

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

Output result:
insert image description here

1.4 Conversion between time and string 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
    }

Output result:
insert image description here

1.5 Time operation - plus the corresponding time LocalDateTime.now().plusYears(2)

LocalDateTime provides a very simple chain call for adding and subtracting date and time, making time calculation very simple:

    @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);
    }

Output result:
insert image description here

1.6 Time calculation - subtract the corresponding time 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);
    }

Output result:
insert image description here

1.7 Two time comparison 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
    }

Output result:

1.8 Use Duration to calculate the time difference Duration.between(of,now).toMillis()

Note that the year and second values ​​of the difference are not calculated. For the number of seconds to be calculated, the conversion can be performed by calculating milliseconds.

    @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
    }

Output result:
insert image description here

1.9 Change the year, month, day, hour, minute, and second of the current time 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);
    }

Output result:
insert image description here

1.10 Custom output format 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);
    }

Output result:
insert image description here

1.11 with() method of LocalDateTime

// 本月第一天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));

Output result:

1.12 Comparison and judgment before and after two dates 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")));
    }
    }

Output result:
insert image description here

2. Util gets the current time

2.1 Date

2.1.1 Date to get the current time

    @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 Defects of Date

Without formatting, the printed date is less readable:

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

Usually SimpleDateFormate is used to implement formatting, but the biggest problem with sdf is that it is not thread-safe.

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)); // 获取当前时间


Summarize

LocalDateTime is very convenient to obtain time and calculate, and it is thread-safe. It is easy to use LocalDateTime.

Guess you like

Origin blog.csdn.net/sunzixiao/article/details/129166030