包括获取当前时间,指定特定时间。进行时间的加减等
LocalDateTime localDateTime3 = LocalDateTime.now(); LocalDate.now(); LocalTime.now(); localDateTime3.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); LocalDateTime localDateTime4 = localDateTime3.minus(23,ChronoUnit.MONTHS); localDateTime4.atZone(ZoneId.systemDefault()); localDateTime4 = localDateTime4.withHour(3); localDateTime4 = localDateTime4.withYear(2016); localDateTime4 = localDateTime4.with(ChronoField.MONTH_OF_YEAR,3)
间隔计算
使用Duration进行 day,hour,minute,second等的计算
使用Period进行Year,Month的计算
Duration duration = Duration.between(localDateTime,localDateTime4); duration.toDays(); duration.toHours(); duration.toMinutes(); Period period2 = Period.between(localDateTime.toLocalDate(),localDateTime4.toLocalDate()); period2.getYears(); period2.getMonths(); period2.toTotalMonths();
与Date的转化,format为String
Date date = Date.from(localDateTime4.atZone(ZoneId.systemDefault()).toInstant()); LocalDateTime dateTime = LocalDateTime.ofInstant(date.toInstant(),ZoneId.systemDefault()); localDateTime3.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
根据需求需要取得当天的零点
-
LocalDateTime today_start = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);//当天零点
-
String td_st_str =
today_start.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
获取当天结束时间
LocalDateTime today_end = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);//当天零点
LocalDateTime与String日期互相转换
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime time = LocalDateTime.now();
String localTime = df.format(time);
LocalDateTime ldt = LocalDateTime.parse("2017-09-28 17:07:05",df);
System.out.println("LocalDateTime转成String类型的时间:"+localTime);
System.out.println("String类型的时间转成LocalDateTime:"+ldt);
控制台结果:
LocalDateTime转成String类型的时间:2017-09-30 10:40:06
String类型的时间转成LocalDateTime:2017-09-28T17:07:05
通过localdatetime获取long型毫秒时间
Long newSecond1 = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();