JDK8:LocalDate,LocalTime,LocalDateTime的使用


1 import org.junit.Test; 2 3 import java.time.LocalDate; 4 import java.time.LocalDateTime; 5 import java.time.LocalTime; 6 7 /**
8 * LocalDate,LocalTime,LocalDateTime的使用 9 * @author fu jingchao 10 * @creat 2021/12/2-17:22 11 */ 12 public class JDK8DateTimeTest { 13 @Test 14 public void test1(){ 15 //now():获取当前的日期、时间、日期+时间 16 LocalDate localDate = LocalDate.now(); 17 LocalTime localTime = LocalTime.now(); 18 LocalDateTime localDateTime = LocalDateTime.now(); 19 System.out.println(localDate);//2021-12-02 20 System.out.println(localTime);//17:43:43.962 21 System.out.println(localDateTime);//2021-12-02T17:43:43.962 22 23 //getXxx():获取相关的属性 24 System.out.println(localDateTime.getDayOfMonth()); 25 System.out.println(localDateTime.getDayOfWeek()); 26 System.out.println(localDateTime.getMonth()); 27 28 //of:指定时间创建对象 29 LocalDateTime localDateTime1 = LocalDateTime.of(2021,12,2,17, 30 50,28); 31 System.out.println(localDateTime1);//2021-12-02T17:50:28 32 33 //体现不可变性 34 //withXxx():设置相关的属性 35 LocalDate localDate1 = localDate.withDayOfMonth(22); 36 System.out.println(localDate);//2021-12-02 37 System.out.println(localDate1);//2021-12-22 38 39 LocalDateTime localDateTime2 = localDateTime.withHour(4);//相当于设置成4点 40 System.out.println(localDateTime);//2021-12-03T14:09:37.680 41 System.out.println(localDateTime2);//2021-12-03T04:09:37.680 42 43 //加 44 LocalDateTime localDateTime3 = localDateTime.plusMonths(3); 45 System.out.println(localDateTime);//2021-12-03T14:09:37.680 46 System.out.println(localDateTime3);//2022-03-03T14:09:37.680 47 48 //减 49 LocalDateTime localDateTime4 = localDateTime.minusDays(3); 50 System.out.println(localDateTime);//2021-12-03T14:13:03.345 51 System.out.println(localDateTime4);//2021-11-30T14:13:03.345 52 } 53 }

 

上一篇:Java日期时间操作基础——包含JDK1.8时间操作新特性


下一篇:LocalDateTime