jdk8獲取當前時間|時間加減|java8時間格式化|時間處理工具|時間比較|線程安全的時間處理方法

目錄

前言

一、jdk8與jdk7以及之前的日期和時間處理類的不同:

二、Java 8日期/時間類

三:日期和時間主要類的關係(待更新)

四:日期操作和處理

獲取當前日期(只能精確到年月日)

獲取當前時間(可以精確到毫秒)

獲取上週週一的日期

獲取具體年、月、日、小時、分鐘、秒

指定日期、時間

判斷兩個日期是否相等

計算幾年後(前)、幾月後(前)、幾天後(前)等的日期

判斷指定月份有多少天

計算兩個日期之間相差月數、天數、分鐘數


前言

在很久之前,我總結了一些jdk7版本之前的關於時間處理的一些公共方法,日期轉換成字符串、指定時間加上指定天數後的日期、獲取上週週一時間 等等;具體的可以戳鏈接查看完整的:https://blog.csdn.net/qq_27471405/article/details/79523556

但是這些是非線程安全的,不建議採用,舉個例子

在一個類中,有以下代碼:
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public String getDate(Date date){
return sdf.format(date);
}

上面這串代碼在併發的時候,是線程不安全的,具體的如何不安全,大家可以搜一下,這裏不多講了

那麼今天給大家分享的是jdk8之後的一些時間處理的公共方法,是線程安全的,理應大家以後應該用下面這些方法

 

一、jdk8與jdk7以及之前的日期和時間處理類的不同:


1. Java的java.util.Date和java.util.Calendar類易用性差,不支持時區,並且是可變的,也就意味着他們都不是線程安全的;
2. 用於格式化日期的類DateFormat被放在java.text包中,它是一個抽象類,所以我們需要實例化一個SimpleDateFormat對象來處理日期格式化,並且DateFormat也是非線程安全,這意味着如果你在多線程程序中調用同一個DateFormat對象,會得到意想不到的結果。
3. 對日期的計算方式繁瑣,而且容易出錯,因爲月份是從0開始的,這意味着從Calendar中獲取的月份需要加一才能表示當前月份
由於以上這些問題,出現了一些三方的日期處理框架,例如Joda-Time,data4j等開源項目


二、Java 8日期/時間類


Java 8的日期和時間類包含LocalDate、LocalTime、Instant、Duration以及Period,這些類都包含在java.time包中。

  • Instant:瞬時實例。

  • LocalDate:本地日期,不包含具體時間 例如:2014-01-14 可以用來記錄生日、紀念日、加盟日等。

  • LocalTime:本地時間,不包含日期。

  • LocalDateTime:組合了日期和時間,但不包含時差和時區信息。

  • ZonedDateTime:最完整的日期時間,包含時區和相對UTC或格林威治的時差。

新API還引入了 ZoneOffSet 和 ZoneId 類,使得解決時區問題更爲簡便。解析、格式化時間的 DateTimeFormatter 類也全部重新設計。

 

三:日期和時間主要類的關係(待更新)

 

1 、LocalDate的關係圖:

2、 LocalTime:

3 、LocalDateTime:

4 、OffsetTime:

5 、OffsetDateTime:

6、 ZonedDateTime:

7 、Instant:

 

四:日期操作和處理

 

獲取當前日期(只能精確到年月日)

/**
     * 獲取當前日期(只能精確到年月日)
     * @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);
    }

如果傳格式化到天小時秒的話,會報異常:Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: HourOfDay

 

獲取當前時間(可以精確到毫秒)

 /**
     * 獲取當前時間(可以精確到毫秒)
     * 原文章鏈接: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);

    }

 

獲取上週週一的日期

/**
     * 獲取上週週一的日期
     * 原文章鏈接: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); 
    }

 

獲取具體年、月、日、小時、分鐘、秒

/**
     * 獲取具體年、月、日、小時、分鐘、秒
     * @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)
    }

 

指定日期、時間

/**
     * 指定日期、時間
     * 原文章鏈接: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);
    }

 

判斷兩個日期是否相等

/**
     * 判斷兩個日期是否相等、之前、之後
     * 原文章鏈接: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));
    }

 

計算幾年後(前)、幾月後(前)、幾天後(前)等的日期

/**
     * 計算幾年後(前)、幾月後(前)、幾天後(前)等的日期
     * 原文章鏈接: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);
    }

 

判斷指定月份有多少天

 /**
     * 判斷指定月份有多少天
     */
    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());
        
    }

 

計算兩個日期之間相差月數、天數、分鐘數

/**
     * 計算兩個日期之間相差月數、天數、分鐘數
     * 原文章鏈接: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)

    }

 

 


參考文章 

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

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

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

感謝原作者的分享,讓技術人能夠更快的解決問題 

我的博客即將同步至騰訊雲+社區,邀請大家一同入駐:https://cloud.tencent.com/developer/support-plan?invite_code=lnlh8qa6e7an

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章