ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] # 方法 ![](https://box.kancloud.cn/ad4796c0f337a52e73522c5bb8465150_921x656.png) # 获取当前时间 ~~~ LocalDate localDate = LocalDate.now(); LocalTime localTime = LocalTime.now(); LocalDateTime localDateTime = LocalDateTime.now(); //当前的年月日 System.out.println(localDate); //当前的时分秒 System.out.println(localTime); //当前的年月日加时分秒 System.out.println(localDateTime); ~~~ 输出 ~~~ 2018-06-06 14:43:04.889017 2018-06-06T14:43:04.889065 ~~~ # of指定时间 ~~~ LocalDate of1 = LocalDate.of(2017, 8, 5); System.out.println(of1); LocalTime of2 = LocalTime.of(5, 11, 20); System.out.println(of2); LocalDateTime of3 = LocalDateTime.of(2017, 8, 5, 11, 11, 23); System.out.println(of3); ~~~ 输出 ~~~ 2017-08-05 05:11:20 2017-08-05T11:11:23 ~~~ # getXxx获取值 ~~~ LocalDateTime localDateTime = LocalDateTime.now(); System.out.println(localDateTime); //getXxx //年份的天数 System.out.println(localDateTime.getDayOfYear()); //月份的天数 System.out.println(localDateTime.getDayOfMonth()); //返回星期几,英文 System.out.println(localDateTime.getDayOfWeek()); //返回月份,因为 System.out.println(localDateTime.getMonth()); //月份 System.out.println(localDateTime.getMonthValue()); //小时 System.out.println(localDateTime.getHour()); //分钟 System.out.println(localDateTime.getMinute()); ~~~ 输出 ~~~ 2018-06-06T14:54:02.650016 157 6 WEDNESDAY JUNE 6 14 54 ~~~ # withXxx修改时间 修改了后会返回新的对象,老的对象不变 体系了日期对象的不可变性 ~~~ LocalDateTime localDateTime = LocalDateTime.now(); System.out.println(localDateTime); //修改月份 LocalDateTime localDateTime1 = localDateTime.withDayOfMonth(20); System.out.println(localDateTime1); //修改小时 System.out.println(localDateTime.withHour(12)); ~~~ 输出 ~~~ 2018-06-06T15:01:43.102993 2018-06-20T15:01:43.102993 2018-06-06T12:01:43.102993 ~~~ # plus添加时间 ~~~ LocalDateTime localDateTime = LocalDateTime.now(); System.out.println(localDateTime); //向前添加3天 LocalDateTime localDateTime1 = localDateTime.plusDays(3); System.out.println(localDateTime1); //向前添加2小时 System.out.println(localDateTime.plusHours(2)); ~~~ 输出 ~~~ 2018-06-06T15:10:56.921629 2018-06-09T15:10:56.921629 2018-06-06T17:10:56.921629 ~~~ # minus减去时间 ~~~ LocalDateTime localDateTime = LocalDateTime.now(); System.out.println(localDateTime); //减去2天 System.out.println(localDateTime.minusDays(2)); //减去3小时 System.out.println(localDateTime.minusHours(3)); ~~~ 输出 ~~~ 2018-06-06T15:12:25.612975 2018-06-04T15:12:25.612975 2018-06-06T12:12:25.612975 ~~~ # 判断时间是不是在之前或者之后 ~~~ LocalDateTime localDateTime = LocalDateTime.now(); //加2天 LocalDateTime localDateTime1 = localDateTime.plusDays(2); //看时间在不在前面 boolean before = localDateTime1.isBefore(localDateTime); //看时间在不在后面 boolean after = localDateTime1.isAfter(localDateTime); //看时间是不是一样 boolean equal = localDateTime1.isEqual(localDateTime); System.out.println(before); System.out.println(after); System.out.println(equal); ~~~ 输出 ~~~ false true false ~~~