根据指定日期/时间创建对象
LocalDate localDate = LocalDate.of(2018, 1, 13);
LocalTime localTime = LocalTime.of(9, 43, 20);
LocalDateTime localDateTime = LocalDateTime.of(2018, 1, 13, 9, 43, 20);
System.out.println(localDate);
System.out.println(localTime);
System.out.println(localDateTime);
运行结果:
日期时间的加减
对于LocalDate,只有精度大于或等于日的加减,如年、月、日;
对于LocalTime,只有精度小于或等于时的加减,如时、分、秒、纳秒;
对于LocalDateTime,则可以进行任意精度的时间相加减;
LocalDateTime localDateTime = LocalDateTime.now();
//以下方法的参数都是long型,返回值都是LocalDateTime
LocalDateTime plusYearsResult = localDateTime.plusYears(2L);
LocalDateTime plusMonthsResult = localDateTime.plusMonths(3L);
LocalDateTime plusDaysResult = localDateTime.plusDays(7L);
LocalDateTime plusHoursResult = localDateTime.plusHours(2L);
LocalDateTime plusMinutesResult = localDateTime.plusMinutes(10L);
LocalDateTime plusSecondsResult = localDateTime.plusSeconds(10L);System.out.println("当前时间是 : " + localDateTime + "\n"+ "当前时间加2年后为 : " + plusYearsResult + "\n"+ "当前时间加3个月后为 : " + plusMonthsResult + "\n"+ "当前时间加7日后为 : " + plusDaysResult + "\n"+ "当前时间加2小时后为 : " + plusHoursResult + "\n"+ "当前时间加10分钟后为 : " + plusMinutesResult + "\n"+ "当前时间加10秒后为 : " + plusSecondsResult + "\n");//也可以以另一种方式来相加减日期,即plus(long amountToAdd, TemporalUnit unit)
// 参数1 : 相加的数量, 参数2 : 相加的单位
LocalDateTime nextMonth = localDateTime.plus(1, ChronoUnit.MONTHS);
LocalDateTime nextYear = localDateTime.plus(1, ChronoUnit.YEARS);
LocalDateTime nextWeek = localDateTime.plus(1, ChronoUnit.WEEKS);System.out.println("now : " + localDateTime + "\n"+ "nextYear : " + nextYear + "\n"+ "nextMonth : " + nextMonth + "\n"+ "nextWeek :" + nextWeek + "\n");//日期的减法用法一样,在此不再举例
运行结果: