1. 程式人生 > >Java8中LocalDate的使用---專案中日期處理

Java8中LocalDate的使用---專案中日期處理

      // 獲取當前日期
        LocalDate now = LocalDate.now();
        // 設定日期
        LocalDate now2 = LocalDate.of(2099, 2, 28);
        // 解析日期,格式必須是yyyy-MM-dd
        LocalDate now3 = LocalDate.parse("2018-01-12");
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        String formatRs = now.format(dtf);
        // 取本月第一天
        LocalDate firstDay = now.with(TemporalAdjusters.firstDayOfMonth());
        LocalDate firstDay2 = now.withDayOfMonth(1);
        // 取本月第2天
        LocalDate secondDay = now.withDayOfMonth(2);
        LocalDate nextMonthDay = now.with(TemporalAdjusters.firstDayOfNextMonth());
        LocalDate nextYearDay = now.with(TemporalAdjusters.firstDayOfNextYear());
        // 明年的這一天
        LocalDate localDate = now.plusYears(1);
        // 當前日期加上往後推20天
        LocalDate plusDate = now.plus(20, ChronoUnit.DAYS);
        LocalDate plusYear = now.plus(10, ChronoUnit.YEARS);
        // 當前日期往前推10天
        LocalDate minusDay = now.minusDays(10);
        LocalDate minusYear = now.minus(10, ChronoUnit.YEARS);
        //localDate轉Date
        ZoneId zoneId = ZoneId.systemDefault();
        ZonedDateTime zdt = now.atStartOfDay(zoneId);
        Instant instant = zdt.toInstant();
        Date fromDate = Date.from(instant);
        // Date轉LocalDate
        Date date = new Date();
        Instant instantToUse = date.toInstant();
        ZoneId zoneIdToUse = ZoneId.systemDefault();
        LocalDate localDateToShow = instantToUse.atZone(zoneIdToUse).toLocalDate();
        // 比較日期大小
        boolean b1 = localDateToShow.equals(LocalDate.of(2018, 04, 27));
        boolean b2= localDateToShow.equals(LocalDate.of(2018, 04, 26));
        // 判斷日期前後  -> false
        boolean b3 = localDateToShow.isAfter(LocalDate.of(2018, 04, 26));//false
        boolean b4 = localDateToShow.isAfter(LocalDate.of(2018, 04, 25));//true
        boolean b5 = localDateToShow.isBefore(LocalDate.of(2018, 04, 26));//false
        boolean b6 = localDateToShow.isBefore(LocalDate.of(2018, 04, 25));//false
        boolean b7 = localDateToShow.isBefore(LocalDate.of(2018, 04, 27));//true
        // 計算兩個日期之間的時間間隔   格式為:x年x月x天
        Period between = Period.between(localDateToShow, LocalDate.of(2018, 05, 28));
        long bwDays = ChronoUnit.DAYS.between(localDateToShow, LocalDate.of(2018, 05, 28));

目前已知:

1、最新JDBC對映將把資料庫的日期型別和Java 8的新型別關聯起來:

SQL -> Java
--------------------------
date -> LocalDate
time -> LocalTime
timestamp -> LocalDateTime
2、框架支援

spring4以支援,mybatis3不支援。