JAVA8新特性隨筆

Instant:瞬時實例
LocalDate:本地日期,不包含具體時間。例如:2014-01-14能夠用來記錄生日、記念日、加盟日等。
LocalTime:本地時間,不包含日期
LocalDateTime:組合了日期和時間,但不包含時差和時區信息
ZonedDateTime:最完整的日期時間,包含時區和相對UTC或格林威治的時差前端

日期類和時間類

  1. ==獲取當前時間==:LocalDateTime.now();
  2. ==日期格式化==::LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss a"));
  3. ==獲取時間戳==:Instant.now()
    Date.from(Instant)將Instant轉換成java.util.Date,Date.toInstant()則是將Date類轉換成Instant類。)
  4. ==LocalDateTime轉String==: LocalDateTime.parse(str,dateTimeFormatter); ==String轉LocalDateTime==: localDateTime.format(dateTimeFormatter);
  5. ==Date轉LocalDateTime==:LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
  6. ==LocalDateTime轉Date==:Date date = Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant());
  7. ==前端傳過來的日期字符串怎麼轉換並放到數據庫==
LocalDate localDate = LocalDate.now();
        System.out.println("LocalDate.now():"+localDate);
        System.out.println("localDate.getYear():"+localDate.getYear());
        System.out.println("localDate.getMonth():"+localDate.getMonth());
        System.out.println("localDate.getMonthValue():"+localDate.getMonthValue());
        System.out.println("localDate.getDayOfMonth():"+localDate.getDayOfMonth());
        System.out.println("localDate.getDayOfWeek():"+localDate.getDayOfWeek());
        System.out.println("localDate.getDayOfWeek().getValue():"+localDate.getDayOfWeek().getValue());

        LocalTime localTime = LocalTime.now();
        System.out.println("當前時間LocalTime.now(): " + localTime);
        System.out.println("當前時間+1小時 localTime.plusHours(1): " + localTime.plusHours(1));

        Clock clock = Clock.systemUTC();
        Clock clock2 = Clock.systemDefaultZone();
        System.out.println("Clock : " + clock.millis());
        System.out.println("clock2 : " + clock2.millis());
        System.out.println("=== 獲取當前的時間戳 ===============================================");
        Instant timestamp = Instant.now();
        System.out.println("獲取當前的時間戳: "+timestamp);
        System.out.println("=== 格式化日期 ===============================================");
        DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss a");
        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println(" LocalDateTime.now(): "+localDateTime);
        System.out.println(" 格式化後的日期:"+localDateTime.format(format));

        System.out.println("=== 檢查生日等週期性事件 ===============================================");
        LocalDate dateOfBirth = LocalDate.of(2019, 7, 25);
        MonthDay birthday = MonthDay.of(dateOfBirth.getMonth(), dateOfBirth.getDayOfMonth());
        MonthDay currentMonthDay = MonthDay.from(localDate);

        if(currentMonthDay.equals(birthday)){
            System.out.println(" Many Many happy returns of the day !!");
        }else{
            System.out.println(" Sorry, today is not your birthday");
        }
相關文章
相關標籤/搜索