localDateTime类
1.分类
将时间分成
localDate类【年月日]】
localTime类【时分秒】
localDateTime类【年月日时分秒】
2.localDateTime类【常用】
(1)构造方法
public class Demo1 {public static void main(String[] args) {//localDateTime[天时分秒]三者使用方法一致,它较为常用//对象获取方法都为静态//now[将当前时间封装为时间对象]LocalDateTime ldt1 = LocalDateTime.now();System.out.println(ldt1);//of[将指定时间封装为时间对象]LocalDateTime ldt2 = LocalDateTime.of(2020, 10, 10, 10, 10, 10);System.out.println(ldt2);}
}打印结果:
-------------------------------------------------------------
2021-06-29T21:08:53.058099600
2020-10-10T10:10:10
(2)成员方法
//localDateTime[天时分秒]的成员方法[字符串需要解析之后才能参入运算]
public class Demo2 {public static void main(String[] args) {LocalDateTime ldt1 = LocalDateTime.of(2020, 10, 10, 10, 10, 10);System.out.println("-----------获取时间的方法--------------------");//getYear[获得年份]System.out.println(ldt1.getYear());//2020//getMonthValue[获得月份]int monthValue = ldt1.getMonthValue();//10System.out.println(monthValue);Month month = ldt1.getMonth();//OCTOBER[返回值类型为枚举]System.out.println(month);// getDayOfMonth[获得一个月的第几天]System.out.println(ldt1.getDayOfMonth());//10System.out.println("-----------增加或者减少时间的方法-------------");LocalDateTime ldt2 = LocalDateTime.of(2020, 10, 10, 10, 10, 10);//增加或者减去年//localDateTime对象调用PlusYear[和获得的方法对应有年月日等的操作]//参数为正,增加年,参数为负,减少年,调用之后会得到一个新的localDateTime对象LocalDateTime ldt3 = ldt2.plusYears(1).plusDays(18);//ldt1.plusDays(18);每次调用会返回一个新的对象,要想在同一个时间上做改动,则打印最后一个对象System.out.println(ldt3);//minusYears减少或增加时间,参数传递的效果和Plus正好相反System.out.println(ldt2.minusYears(1));System.out.println("-----------修改时间的方法--------------------");LocalDateTime ldt4 = LocalDateTime.of(2020, 10, 10, 10, 10, 10);//修改年//localDateTime对象调用withYear(int Year)[和获得的方法对应有年月日等的操作]//调用之后会得到一个新的localDateTime对象LocalDateTime ldt5 = ldt4.withYear(2000);System.out.println(ldt5);//如果修改的年月日超过范围则会报错System.out.println(ldt5.withMonth(8));}
}打印结果:
-----------获取时间的方法--------------------
2020
10
OCTOBER
10
-----------增加或者减少时间的方法-------------
2021-10-28T10:10:10
2019-10-10T10:10:10
-----------修改时间的方法--------------------
2000-10-10T10:10:10
2000-08-10T10:10:10