JDK 8中的日期时间API

 


1
import org.junit.Test;
2 3 import java.time.LocalDate; 4 import java.time.LocalDateTime; 5 import java.time.LocalTime; 6 import java.util.Date; 7 8 /** 9 * jdk 8中日期时间API的测试 10 * 11 * @author kai 12 * @create 2021-09-15 08:44 13 **/ 14 public class JDK8DateTimeTest { 15 16 @Test 17 public void testDate(){ 18 //偏移量 19 Date date1 = new Date(2002 - 1900,10 - 1,8); 20 System.out.println(date1);//Tue Oct 08 00:00:00 CST 2002 21 22 } 23 24 /* 25 LocalDate、LocalTime、LocalDateTime 的使用 26 27 */ 28 @Test 29 public void test1(){ 30 //now():获取当前日期、时间、日期+时间
31 LocalDate localDate = LocalDate.now(); 32 LocalTime localTime = LocalTime.now(); 33 LocalDateTime localDateTime = LocalDateTime.now(); 34 35 System.out.println(localDate);//2021-09-15 36 System.out.println(localTime);//09:01:04.092 37 System.out.println(localDateTime);//2021-09-15T09:01:04.092 38 } 39 }

of () ; 方法

LocalDateTime localDateTime1 = LocalDateTime.of( year , month , dayOfMonth );

设置指定的年、月、日、时、分、秒。没有偏移量( 1990年为初始, 月份0 是一月 , 日 无偏移)。

getXXX()   ...  ;方法

LocalDateTime localDateTime1 = LocalDateTime.of(2002,10,8,13,55);

       System.out.println(localDateTime1.getDayOfMonth());//8
       System.out.println(localDateTime1.getDayOfWeek());//TUESDAY
    System.out.println(localDateTime1.getMonth());//OCTOBER
       System.out.println(localDateTime1.getMonthValue());//10
       System.out.println(localDateTime1.getMinute());//55

withXXX() ... ; 方法

LocalDate localDate1 = localDate.withDayOfMonth( 22 ); 

不可变性!!!

(原有日期不变,返回值日期改变)

LocalDate localDate1 = localDate.withDayOfMonth(22);
        System.out.println(localDate);//2021-9-15
        System.out.println(localDate1);//2021-9-22

plusXXX() ... ; 方法

LocalDateTime localDateTime2 = localDateTime.plusMonths(3);

给指定的年、月、日、时、分、秒,上对应的值

LocalDateTime localDateTime2 = localDateTime.plusMonths(3);
        System.out.println(localDateTime);//2021-09-15T13:53:55.371
        System.out.println(localDateTime2);//2021-12-15T13:53:55.371

minusXXX() ... ; 方法

LocalDateTime localDateTime3 = localDateTime.minusDays(6);

给指定的年、月、日、时、分、秒,去对应的值

LocalDateTime localDateTime3 = localDateTime.minusDays(6);
        System.out.println(localDateTime);//2021-09-18T08:28:27.039
        System.out.println(localDateTime3);//2021-09-12T08:28:27.039

总结

  1. LocalDateTime相较于LocalDate、LocalTime,使用频率要高

     2. 类似于Calendar

 

posted @ 2021-09-18 08:37  翼`  阅读(37)  评论(0编辑  收藏  举报