jdk8 新特性之 LocalDateTime
一、创建LocalDateTime的方式
//当前时间创建 LocalDateTime bjTime = LocalDateTime.now(); //指定时区创建 LocalDateTime lsjTime = LocalDateTime.now(ZoneId.of("America/Los_Angeles")); DateTimeFormatter sdf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); //默认格式,字符串创建 LocalDateTime zd1 = LocalDateTime.parse("2020-12-14T12:00:50"); //指定字符串,指定模式创建 LocalDateTime zd2 = LocalDateTime.parse("2020-12-08 17:30:50", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); System.out.println("北京时间:"+sdf.format(bjTime)); System.out.println("洛杉矶时间:"+ sdf.format(lsjTime) ); System.out.println("指定时间"+zd1); System.out.println("指定时间2"+zd2); System.out.println("当前年份:"+bjTime.getYear()+",当前月份:"+bjTime.getMonth()+",当前天数:"+bjTime.getDayOfMonth()); System.out.println("当前周几:"+bjTime.getDayOfWeek()+",当前时间:"+bjTime.getHour()+",当前分钟:"+bjTime.getMinute()+",当前秒数:"+bjTime.getSecond());
二、时间增加、减少操作
LocalDateTime bjTime2 = bjTime.plusYears(1); System.out.println("增加一年时间:"+bjTime2); bjTime2=bjTime.plusWeeks(2); System.out.println("增加2个星期:"+bjTime2); bjTime2=bjTime.plusMonths(1); System.out.println("增加一个月时间:"+bjTime2); bjTime2 = bjTime.plusHours(10); System.out.println("增加是10个小时:"+bjTime2);
三、修改时间的年、月、日、时、分、秒
//修改年份 bjTime2 = bjTime.withYear(2024); System.out.println("修改年份"+bjTime2); //当天零时零分零秒 bjTime2 = bjTime.withHour(0).withMinute(0).withSecond(0).withMinute(0); System.out.println("当天零时零零秒"+bjTime2); //第二天零时零分零秒 bjTime2 =bjTime.plusDays(1).withHour(0).withMinute(0); System.out.println("第二天零时零分零秒"+bjTime2); LocalDate localDate = bjTime2.toLocalDate(); System.out.println("当天零时零零秒"+localDate);
四、求时间相差年份、月数、天数、小时数、分钟数
//相差天数、月份、天数、秒数计算 bjTime2 = bjTime.plusDays(40); System.out.println("相差天数"+bjTime2.until(bjTime, ChronoUnit.DAYS)); System.out.println("相差月份"+bjTime2.until(bjTime, ChronoUnit.MONTHS)); System.out.println("相差小时:"+bjTime2.until(bjTime, ChronoUnit.HOURS)); System.out.println("相差秒数:"+bjTime2.until(bjTime, ChronoUnit.MILLIS));
五、
时间类的相互转换
1. 转换成LocalDate与LocalTime
localDateTime.toLocalDate();localDateTime.toLocalTime();
posted on 2022-05-06 18:05 topguntopgun 阅读(249) 评论(0) 编辑 收藏 举报