LocalDateTime.now()时间处理jdk1.8日期便捷处理类java.time.LocalDateTime;
//获取当前时间 System.out.println(LocalDateTime.now()); //获取当前时间时分秒 System.out.println(LocalDateTime.now().toLocalTime()); //获取当前时间年月日
System.out.println(LocalDateTime.now().toLocalDate()); //获取当前时间20天之前 System.out.println(LocalDateTime.now().minusDays(20)); //获取当前时间20天之后 System.out.println(LocalDateTime.now().plusDays(20)); //获取当前时间60天之前 System.out.println(LocalDateTime.now().minusDays(60)); //所有minus开头都是之前 plus开头都是之后 //比较大小 System.out.println(LocalDateTime.now().compareTo(LocalDateTime.now().plusDays(2)));
//获取当天的开始时间
LocalDateTime.now().toLocalDate().atStartOfDay()
//实例化方式 以及比较大小 Duration between = Duration.between(LocalDateTime.of(1993,3,14,0,0), LocalDateTime.now()); Duration between2 = Duration.between(LocalDateTime.of(1993,3,14,0,0), LocalDateTime.now()); System.out.println(between.toDays()); System.out.println(between2.toDays());
Period基于年、月、日期值,而Duration基于时间值。
Period 类
Period 类表示一段时间的年、月、日,使用between()方法获取两个日期之间的差作为Period 对象返回:
java.time.Duration duration = java.time.Duration.between(LocalDateTime startTime, LocalDateTime endTime ); 例如: duration.toMinutes() //两个时间差的分钟数 toNanos()//纳秒 toMillis()//毫秒 toMinutes()//分钟 toHours()//小时 toDays()//天数
//获取当前是第几日 System.out.println(LocalDateTime.now().getDayOfMonth()); //获取当前周几 System.out.println(LocalDateTime.now().getDayOfWeek().getValue()); //获取当前是今年第几天 System.out.println(LocalDateTime.now().getDayOfYear());
//获取当前是今年第几周
int i = pwPlanDayPO.getWorkBeginDate().get(WeekFields.ISO.weekOfWeekBasedYear());
//获取毫秒数 Long milliSecond = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
1.获取当前年月日的字符串
String ymd = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
解析时间
private LocalDateTime getTime(){ DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime parse = LocalDateTime.parse(startDate, df); return parse; }
时间格式
String s="yyyy-MM-dd'T'HH:mm:ss.SSS+SSSS"; LocalDateTime parse = LocalDateTime.parse("2022-06-17T07:33:00.000+0000", DateTimeFormatter.ofPattern(s)); System.out.println(parse);