jdk8 get current time|time addition and subtraction|java8 time format|time processing tool|time comparison|thread-safe time processing method

table of Contents

Preface

1. The difference between jdk8 and jdk7 and the previous date and time processing class:

Two, Java 8 date/time class

Three: the relationship between date and time of the main category (to be updated)

Four: Date operation and processing

Get the current date (only accurate to year, month and day)

Get the current time (can be accurate to milliseconds)

Get the date of the last Monday

Get specific year, month, day, hour, minute, second

Specify date and time

Determine whether two dates are equal

Calculate dates in a few years (before), months (before), days (before), etc.

Determine how many days there are in a specified month

Calculate the number of months, days, and minutes between two dates


Preface

A long time ago, I summarized some of the public methods of time processing before the jdk7 version, such as converting dates into strings, specifying the time plus the date after the specified number of days, obtaining the Monday time of the previous week, etc.; you can click the link to view the details. Complete: https://blog.csdn.net/qq_27471405/article/details/79523556

But these are not thread-safe and not recommended, for example

In a class, there is the following code:
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public String getDate(Date date){ return sdf.format(date); }

The above code is thread-unsafe when it is concurrent. You can search for specific details. I won’t talk about it here.

So today I will share with you some public methods of time processing after jdk8, which are thread-safe, and you should use the following methods in the future

 

1. The difference between jdk8 and jdk7 and the previous date and time processing class:


1. Java's java.util.Date and java.util.Calendar classes are not easy to use, do not support time zones, and are variable, which means that they are not thread-safe;
2. Classes for formatting dates DateFormat is placed in the java.text package, it is an abstract class, so we need to instantiate a SimpleDateFormat object to handle date formatting, and DateFormat is also non-thread-safe, which means that if you call the same in a multi-threaded program DateFormat object, will get unexpected results.
3. The calculation of the date is cumbersome and error-prone, because the month starts from 0, which means that the month obtained from the Calendar needs to be increased by one to represent the current month.
Due to the above problems, there have been some tripartite date processing frameworks. , Such as Joda-Time, data4j and other open source projects


Two, Java 8 date/time class


Java 8 date and time classes include LocalDate, LocalTime, Instant, Duration, and Period, which are all included in the java.time package.

  • Instant: Instant instance.

  • LocalDate: local date, excluding specific time. For example: 2014-01-14 can be used to record birthdays, anniversaries, joining days, etc.

  • LocalTime: local time, excluding date.

  • LocalDateTime: a combination of date and time, but does not include time difference and time zone information.

  • ZonedDateTime: The most complete date and time, including the time zone and the time difference relative to UTC or Greenwich.

The new API also introduces the ZoneOffSet and ZoneId classes, making it easier to solve the time zone problem. The DateTimeFormatter class for parsing and formatting time has also been completely redesigned.

 

Three: the relationship between date and time of the main category (to be updated)

 

1. The relationship diagram of LocalDate:

2、 LocalTime:

3 、 LocalDateTime :

4 、OffsetTime:

5 、OffsetDateTime:

6、 ZonedDateTime:

7 、Instant:

 

Four: Date operation and processing

 

Get the current date (only accurate to year, month and day)

/**
     * 获取当前日期(只能精确到年月日)
     * @param formatStr
     */
    public static void getNowDate(String formatStr){
        if (StringUtils.isBlank(formatStr)){
            formatStr = "yyyy-MM-dd";
        }
        LocalDate now = LocalDate.now();
        System.out.println("当前日期: " + now + " " + now.getDayOfWeek());
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(formatStr);                        // * 原文章链接:https://blog.csdn.net/qq_27471405/article/details/106824023   * 其他均为盗版,公众号:灵儿的笔记(zygxsq)
        String nowFormat = now.format(dateTimeFormatter);
        System.out.println("格式化后的当前日期:"+nowFormat);
    }

If it is formatted to days, hours and seconds, an exception will be reported: Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: HourOfDay

 

Get the current time (can be accurate to milliseconds)

 /**
     * 获取当前时间(可以精确到毫秒)
     * 原文章链接:https://blog.csdn.net/qq_27471405/article/details/106824023
     * 其他均为盗版,公众号:灵儿的笔记(zygxsq)
     * @param formatStr
     */
    public static void getNowTime(String formatStr){
        if (StringUtils.isBlank(formatStr)){
            formatStr = "yyyy-MM-dd";
        }
        LocalDateTime now = LocalDateTime.now();
        System.out.println("当前日期: " + now + " " + now.getDayOfWeek());
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(formatStr);                      // * 原文章链接:https://blog.csdn.net/qq_27471405/article/details/106824023    * 其他均为盗版,公众号:灵儿的笔记(zygxsq)

        String nowFormat = now.format(dateTimeFormatter);
        System.out.println("格式化后的当前日期:"+nowFormat);

    }

 

Get the date of the last Monday

/**
     * 获取上周周一的日期
     * 原文章链接:https://blog.csdn.net/qq_27471405/article/details/106824023
     * 其他均为盗版,公众号:灵儿的笔记(zygxsq)
     */
    public static void getLastMonday(){
        LocalDate now = LocalDate.now();
        System.out.println("当前日期: " + now + " " + now.getDayOfWeek());
        LocalDate todayOfLastWeek = now.minusDays(7);
        LocalDate last_monday = todayOfLastWeek.with(TemporalAdjusters.previous(DayOfWeek.SUNDAY)).plusDays(1); // * 原文章链接:https://blog.csdn.net/qq_27471405/article/details/106824023   * 其他均为盗版,公众号:灵儿的笔记(zygxsq)
        System.out.println("上周周一日期:"+last_monday); 
    }

 

Get specific year, month, day, hour, minute, second

/**
     * 获取具体年、月、日、小时、分钟、秒
     * @param formatStr
     */
    public static void getDetailTime(String formatStr){
        LocalDateTime now = LocalDateTime.now();
        System.out.println("当前日期: " + now + " " + now.getDayOfWeek());
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(formatStr);

        String nowFormat = now.format(dateTimeFormatter);
        System.out.println("格式化后的当前日期:"+nowFormat);

        int year = now.getYear();
        int month = now.getMonthValue();
        int day = now.getDayOfMonth();
        int hour = now.getHour();
        int minute = now.getMinute();
        int second = now.getSecond();
        int nano = now.getNano();
        
        System.out.printf("年 : %d  月 : %d  日 : %d  小时:%d 分钟:%d 秒:%d  毫秒:%d %n", year, month, day,hour,minute,second,nano);  // * 原文章链接:https://blog.csdn.net/qq_27471405/article/details/106824023   * 其他均为盗版,公众号:灵儿的笔记(zygxsq)
    }

 

Specify date and time

/**
     * 指定日期、时间
     * 原文章链接:https://blog.csdn.net/qq_27471405/article/details/106824023
     * 其他均为盗版,公众号:灵儿的笔记(zygxsq)
     * @param formatStr
     */
    public static void createTime(String formatStr){
        LocalDate date = LocalDate.of(2020, 04, 27);
        System.out.println("指定日期: " + date);
        LocalDateTime time = LocalDateTime.of(2020, 04, 27,06,10,50);
        System.out.println("指定时间: " + time);

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(formatStr);
        String nowFormat = time.format(dateTimeFormatter);
        System.out.println("格式化后的指定时间:"+nowFormat);
    }

 

Determine whether two dates are equal

/**
     * 判断两个日期是否相等、之前、之后
     * 原文章链接:https://blog.csdn.net/qq_27471405/article/details/106824023
     * 其他均为盗版,公众号:灵儿的笔记(zygxsq)
     */
    public static void compareDate(){
        LocalDate now = LocalDate.now();
        System.out.println("当前时间: " + now + " " + now.getDayOfWeek());
        LocalDate date1 = LocalDate.of(2020, 04, 27);
        LocalDate date2 = LocalDate.of(2020, 04, 27);
        LocalDate date3 = LocalDate.of(2020, 04, 28);

        boolean equal = now.isEqual(date1);
        System.out.printf("是否是同一时间:%s ", date1.equals(now));
        System.out.printf("是否是同一时间:%s ", now.isEqual(date1));

        System.out.println();
        System.out.printf("是否是同一时间:%s ", date1.equals(date2));
        System.out.printf("是否是同一时间:%s ", date1.isEqual(date2));
        System.out.println();
        System.out.println("data2(2020.4.27)是否比data3(2020.4.28)小: "+date2.isBefore(date3));             * 原文章链接:https://blog.csdn.net/qq_27471405/article/details/106824023   * 其他均为盗版,公众号:灵儿的笔记(zygxsq)
        System.out.println("data2(2020.4.27)是否比data3(2020.4.28)大: "+date2.isAfter(date3));
    }

 

Calculate dates in a few years (before), months (before), days (before), etc.

/**
     * 计算几年后(前)、几月后(前)、几天后(前)等的日期
     * 原文章链接:https://blog.csdn.net/qq_27471405/article/details/106824023
     * 其他均为盗版,公众号:灵儿的笔记(zygxsq)
     * @param formatStr
     */
    public static void calculateTime(String formatStr){
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime newTime = now.plusHours(6);

        System.out.println("当前时间: " + now + " " + now.getDayOfWeek());
        System.out.println("6小时后的时间: " +  newTime);
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(formatStr);
        String nowFormat = now.format(dateTimeFormatter);
        String newFormat = newTime.format(dateTimeFormatter);
        System.out.println("格式化后的当前时间:"+nowFormat);
        System.out.println("格式化后的6小时后的时间:"+newFormat);

        LocalDateTime twoYearsLater = now.plusYears(2);
        String twoYearsFormat = twoYearsLater.format(dateTimeFormatter);
        System.out.println("2年后的时间:"+twoYearsFormat);

        LocalDateTime twoMonthsLater = now.plusMonths(2);
        String twoMonthsFormat = twoMonthsLater.format(dateTimeFormatter);
        System.out.println("2个月后的时间:"+twoMonthsFormat);

        LocalDateTime twoWeeksLater = now.plusWeeks(2);
        String twoWeeksFormat = twoWeeksLater.format(dateTimeFormatter);
        System.out.println("2周后的时间:"+twoWeeksFormat);

        LocalDateTime twoDaysLater = now.plusDays(2);
        String twoDaysFormat = twoDaysLater.format(dateTimeFormatter);
        System.out.println("2天后的时间:"+twoDaysFormat);

        LocalDateTime twoMinutesLater = now.plusMinutes(2);
        String twoMinutesFormat = twoMinutesLater.format(dateTimeFormatter);
        System.out.println("2分钟后的时间:"+twoMinutesFormat);

        LocalDateTime twoMinutesBefore = now.plusMinutes(-2);
        String twoMinutesBeforeFormat = twoMinutesBefore.format(dateTimeFormatter);
        System.out.println("2分钟前的时间:"+twoMinutesBeforeFormat);

        //原文章链接:https://blog.csdn.net/qq_27471405/article/details/106824023
        //其他均为盗版,公众号:灵儿的笔记(zygxsq)
        //还可以直接通过plus方法计算 几年(月周天)后
        LocalDateTime twoYearsPlusLater = now.plus(2, ChronoUnit.YEARS);
        String twoYearsPlusLaterFormat = twoYearsPlusLater.format(dateTimeFormatter);
        System.out.println("2年后的时间:"+twoYearsPlusLaterFormat);

        //负号表示 之前
        LocalDateTime twoDaysPlusBefore = now.plus(-2, ChronoUnit.DAYS);
        String twoDaysPlusBeforeFormat = twoDaysPlusBefore.format(dateTimeFormatter);
        System.out.println("2天前的时间:"+twoDaysPlusBeforeFormat);
        //也可以用minus,也表示之前
        LocalDateTime twoDaysMinusBefore = now.minus(2, ChronoUnit.DAYS);
        String twoDaysMinusBeforeFormat = twoDaysMinusBefore.format(dateTimeFormatter);
        System.out.println("2天前的时间:"+twoDaysMinusBeforeFormat);
    }

 

Determine how many days there are in a specified month

 /**
     * 判断指定月份有多少天
     */
    public static void getMonthDays(){
        YearMonth currentYearMonth = YearMonth.now();
        System.out.println("当前时间:"+currentYearMonth);
        System.out.println("当前月份有多少天:"+currentYearMonth.lengthOfMonth());

        YearMonth february = YearMonth.of(2020, Month.FEBRUARY);
        System.out.println("指定时间的月份2月:"+february);
        System.out.println("指定时间的月份2月有多少天:"+february.lengthOfMonth());
        
    }

 

Calculate the number of months, days, and minutes between two dates

/**
     * 计算两个日期之间相差月数、天数、分钟数
     * 原文章链接:https://blog.csdn.net/qq_27471405/article/details/106824023
     * 其他均为盗版,公众号:灵儿的笔记(zygxsq)
     */
    public static void getDaysBetweenTwoDate(){
        LocalDate startDate = LocalDate.of(2020, 04, 27);
        LocalDate endDate = LocalDate.of(2020, 07, 2);

        long months = startDate.until(endDate, ChronoUnit.MONTHS);
        long days = startDate.until(endDate, ChronoUnit.DAYS);
        System.out.println("startDate(2020.04.27)和endDate(2020.07.02)相差月数:"+months);
        System.out.println("startDate(2020.04.27)和endDate(2020.07.02)相差天数:"+days);

        LocalDateTime startTime = LocalDateTime.of(2020, 04, 27,18,20,10);
        LocalDateTime endTime = LocalDateTime.of(2020, 04, 27,18,30,12);
        long minutes = startTime.until(endTime, ChronoUnit.MINUTES);
        System.out.println("startTime(2020.04.27 18:20:10)和endTime(2020.04.27 18:30:20)相差分钟数:"+minutes); // * 原文章链接https://blog.csdn.net/qq_27471405/article/details/106824023 * 其他均为盗版,公众号:灵儿的笔记(zygxsq)

    }

 

 


Reference article 

https://blog.csdn.net/u012091080/article/details/79901830

https://blog.csdn.net/chenleixing/article/details/44408875

https://blog.csdn.net/feicongcong/article/details/78224494

Thanks to the original author for sharing, so that technical people can solve the problem faster 

My blog will be synced to Tencent Cloud + community soon, and everyone is invited to join: https://cloud.tencent.com/developer/support-plan?invite_code=lnlh8qa6e7an

Guess you like

Origin blog.csdn.net/qq_27471405/article/details/106824023