Java8 新特性 Data Time API

Java8新的日期類型

在Java8之前,Date日期API對咱們很是的不友好,它沒法表示日期,只能以毫秒的精試來表示時間,而且能夠修改,他的線程還不是安全的。因此Java8中引入了全新的日期和時間API就是爲了解決這一問題。html

LocalDate,LocalTime,LocalDateTime的簡單使用

  使用靜態工廠of,來建立一個LocalDate實例。java

@Test
public void test1() {
    LocalDate of = LocalDate.of(2019, 11, 11);//2019-11-11
    int year = of.getYear();                //年份:2019
    Month month = of.getMonth();             //月份:NOVEMBER
    int dayOfMonth = of.getDayOfMonth();    //這月的第幾天:11
    DayOfWeek dayOfWeek = of.getDayOfWeek();//這周的第幾天:MONDAY
    int dayOfYear = of.getDayOfYear();      //這年的第幾天:315
    boolean leapYear = of.isLeapYear();     //是不是潤年:false
}

  使用靜態工廠of,來建立一個LocalTime實例安全

@Test
public void test2() {
    LocalTime localTime = LocalTime.of(11, 12, 13);
    int hour = localTime.getHour();         //小時:11
    int minute = localTime.getMinute();     //分鐘:12
    int second = localTime.getSecond();     //秒數:13
}

  使用靜態工廠of,來建立一個LocalDateTime實例spa

@Test
public void test3() {
    //2019-11-12T13:14:15
    LocalDateTime localDateTime = LocalDateTime.of(2019, 11, 12, 13, 14, 15);
    //2019-11-12
    LocalDate localDate = localDateTime.toLocalDate();
    //13:14:15
    LocalTime localTime = localDateTime.toLocalTime();
    //能夠從LocalDateTime獲取全部的當前的信息,好比,年份,月份。。
    LocalDateTime now = LocalDateTime.now(); //獲取當前系統的日期,時間
}

格式化日期類型和解晰符串

@Test
public void test4() {
    LocalDateTime localDateTime = LocalDateTime.now();
    String format = localDateTime.format(DateTimeFormatter.BASIC_ISO_DATE); 
    //20191210
    String format1 = localDateTime.format(DateTimeFormatter.ISO_DATE_TIME); 
    //2019-12-10T09:35:22.27
    String format2 = localDateTime.format(DateTimeFormatter.ISO_DATE);      
    //2019-12-10
    String format3 = localDateTime.format(DateTimeFormatter.ISO_TIME);      
    //09:37:52.778

    //自定義規則
    String format4 = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); 
    //2019-12-10 09:39:18
    String format5 = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")); 
    //2019-12-10
    String format6 = localDateTime.format(DateTimeFormatter.ofPattern("HH:mm:ss")); 
    //09:40:06
    
    //解晰字符串
    String mYDateTime = "2019-12-10 09:39:18";
    String mYDate = "2019-12-10";
    LocalDate parse = LocalDate.parse(mYDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    //2019-12-10
    LocalDateTime parse1 = LocalDateTime.parse(mYDateTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    //2019-12-10T09:39:18
}

參考:線程

java8新特性七-Date Time APIcode

<br> <hr> <center>orm

細節決定成敗! 我的愚見,若有不對,懇請扶正!htm

</center>blog

相關文章
相關標籤/搜索