java8新特性之time

java8新特性之time


java 8提供了java.time包來表示、操作時間。主要涉及到了date、time、instant、duration、timezone的概念。這些時間類都是基於ISO日曆系統的。這些時間類都是不可變的,因此也是線程安全的。

在java8之前,時間類有java.util下的Date、Calendar等類提供。但是由於它們類型不安全、線程不安全(可變的)、易出bug(比如不常用的月份編號方式)等問題,導致這些遺留類不在常用。

廢話不說,直接上代碼

public void testLocalDateTime()
    {
        LocalDateTime currentTime = LocalDateTime.now();
        System.out.println("當前時間: " + currentTime);
        
        ZoneId zone = ZoneId.systemDefault();
        Instant instant = currentTime.atZone(zone).toInstant();
        System.out.println("當前時間轉毫秒: " + instant.toEpochMilli());
        
        LocalDate date1 = currentTime.toLocalDate();
        System.out.println("date1: " + date1);
        
        Month month = currentTime.getMonth();
        int day = currentTime.getDayOfMonth();
        int seconds = currentTime.getSecond();
        System.out.println("月: " + month + ", 日: " + day + ", 秒: " + seconds);
        
        LocalDateTime date2 = currentTime.withDayOfMonth(10).withYear(2012);
        System.out.println("date2: " + date2);
        
        Period period2 = Period.between(date1, date2.toLocalDate());
        System.out.println(period2.getYears());
        System.out.println(period2.getMonths());
        System.out.println(period2.toTotalMonths());
        
        LocalDate date3 = LocalDate.of(2014, Month.DECEMBER, 12);
        System.out.println("date3: " + date3);
        
        LocalTime date4 = LocalTime.of(22, 15);
        System.out.println("date4: " + date4);
        
        LocalTime date5 = LocalTime.parse("20:15:30");
        System.out.println("date5: " + date5);
    }
    
    public void testZonedDateTime()
    {
        ZonedDateTime date1 = ZonedDateTime.parse("2015-12-03T10:15:30+05:30[Asia/Shanghai]");
        System.out.println("date1: " + date1);
        
        ZoneId id = ZoneId.of("Europe/Paris");
        System.out.println("ZoneId: " + id);
        
        ZoneId currentZone = ZoneId.systemDefault();
        System.out.println("當期時區: " + currentZone);
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章