JavaSE常用类之JDK8中Date相关类的常用方法

JDK8 中用到的 Date 类

LocalDate、LocalTime、LocalDateTime 之间的区别

这三种类顾名思义就是三种不同的表述时间的方式,LocalDate 即日期相关、LocalTime 即时间相关、LocalDateTime 即日期时间一起出现。

now( ) 方法获取当前时间

//获取当前的日期、时间、日期 + 时间
LocalDate localDate = LocalDate.now();
LocalTime localTime = LocalTime.now();
LocalDateTime localDateTime = LocalDateTime.now();

System.out.println(localDate);		//2021-03-09
System.out.println(localTime);		//09:50:24.084
System.out.println(localDateTime);		//2021-03-09T09:50:24.084

of( ) 方法设置指定的年、月、日、时、分、秒

//of() 设置指定的年、月、日、时、分、秒
LocalDateTime localDateTime1 = LocalDateTime.of(2021, 3, 8, 17, 35, 1);
System.out.println(localDateTime1);		//2021-03-08T17:35:01

getXxx( ) 方法获取相关属性

//getXxx() 获取相关属性
System.out.println(localDateTime.getYear());   //yyyy
System.out.println(localDateTime.getDayOfMonth()); //dd
System.out.println(localDateTime.getDayOfWeek());  //MON or Tue...
System.out.println(localDateTime.getMonth());     //March or April...
System.out.println(localDateTime.getMonthValue()); //mm
System.out.println(localDateTime.getMinute());    //分钟

withXxx( ) 方法设置相关属性

//withXxx() 设置相关属性      
LocalDate localDate1 = localDate.withDayOfMonth(1);			//不可变性
System.out.println(localDate);    //当前日期		2021-03-09
System.out.println(localDate1);       //设置为 1号的日期		2021-03-01

plusXxx( ) 方法

//plusXxx()
LocalDate localDate2 = localDate.plusMonths(5);		//往后添加5个月
System.out.println(localDate2);			//2021-08-09
上一篇:JAVA核心技术I---JAVA基础知识(工具类Arrays和Collections类)


下一篇:Job for dhcpd.service failed because the control process exited with error code. See "systemctl