注意!Local*在
JDK8
以上有效
LocalDate
、LocalTime
、LocalDateTime
作为JDK8
新添加的方法,在处理本地日期、本地时间以及本地日期时间等问题上更加友好,是一个真正的类似于现实世界的日历对象
,相较于Date
、Calendar
于公历相对,没有偏移量:
星期一就是星期一,1月就是1,2020年就是2020
并且具有不可变性,在进行设置或者参照对象,原对象依然不变。
以下
*
代指Date、Time、DateTime
一、构造方法
获取当前时间或者设置一个时间:
Local*.now()
获取当前时间Local*.of(y,m,d,h,m,s)
设置一个时间
/* Local*.now() 获取当前的时间/日期 */
LocalDate date=LocalDate.now();
LocalTime localTime = LocalTime.now();
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(date);
System.out.println(localTime);
System.out.println(localDateTime);
运行效果如下:
/* .of 设置指定的时间 没有偏移量 */
date=LocalDate.of(2020,6,6);
localTime=LocalTime.of(23,23,23);
localDateTime=LocalDateTime.of(2020,6,6,6,6,6);
System.out.println(date);
System.out.println(localTime);
System.out.println(localDateTime);
运行结果:![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/2322af6ed3f1d3313ef0d700a57f65ca.png)
二、get方法:
用于获取当前时间对象在日期中的具体参数:
.getDayOfMonth()
, 获取当前是本月的第N天.getDayOfYear()
,获取当前是本年的第N天.getDayOfWeek()
,获取当前是星期几.getDayOfWeek()
,获取当前是星期几.getMonth()
,获取当前第N月.getMonthValue()
,获取当前月名称(英文).getMinute()
,获取当前分钟
/* get 获取 */
System.out.println(localDateTime.getDayOfMonth());
System.out.println(localDateTime.getDayOfWeek());
System.out.println(localDateTime.getDayOfYear());
System.out.println(localDateTime.getMonth());
System.out.println(localDateTime.getMonthValue());
System.out.println(localDateTime.getMinute());
运行效果:
三、with方法
用来以当前时间对象为基础,获取另一个对象,原本的对象不会改变
:
.withDayOfMonth()
获取当月第N天的时间对象.withDayOfYear()
获取当年第N天的时间对象.withYear()
获取当前日期在第N年的时间对象
/* with方法 不可变性 */
LocalDateTime localDateTime1 = localDateTime.withDayOfMonth(22);
System.out.println(localDateTime1);
LocalDateTime localDateTime2 = localDateTime.withYear(1998);
System.out.println(localDateTime2);
运行效果:
四、plus方法
用来以当前时间对象为基础 加上一个参数后的时间对象,原本的对象不会改变
:
plusYears()
当前时间对象N年后的时间对象plusHours()
当前时间对象N小时后的时间对象
LocalDateTime localDateTime3 = localDateTime.plusYears(2);
LocalDateTime localDateTime4 = localDateTime.plusHours(2);
System.out.println(localDateTime3);
System.out.println(localDateTime4);
运行效果:
五、minus方法
用来以当前时间对象为基础,减去一个参数后的时间对象,原本的对象不会改变
:
minusDays()
当前时间对象,N天前的时间对象minusHours()
当前时间对象,N小时前的时间对象
/* minus */
LocalDateTime localDateTime5 = localDateTime.minusDays(5);
LocalDateTime localDateTime6 = localDateTime.minusYears(5);
System.out.println(localDateTime5);
System.out.println(localDateTime6);