JDK1.8中增加的日期时间工具类
操作日期类LocalDate
太方便了,提供了非常多的方法,比之前的DateFormat好用多了,直接上代码
//给定日期
LocalDate date=LocalDate.of(2018,12,2);
System.out.println(date);
System.out.println(date.getYear());//取年份
System.out.println(date.getMonthValue());//取月份
System.out.println(date.getDayOfMonth());//取日期
System.out.println(date.getDayOfWeek().getValue());//取星期
//格式化日期
String dateValue=date.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日"));
System.out.println(dateValue);
//判断润年
System.out.println(date.isLeapYear());
//根据日期字符串构造
LocalDate date1=LocalDate.parse("2020-08-02");
System.out.println(date1);
LocalDate date2= LocalDate.now();
//取本月第1天
System.out.println(date2.with(TemporalAdjusters.firstDayOfMonth()));
//取本月最后1天
System.out.println(date2.with(TemporalAdjusters.lastDayOfMonth()));
//取本月指定天数
System.out.println(date2.withDayOfMonth(10));
//取下n天
System.out.println(date2.plusDays(365));
//取给定时间月份的第一个周一
System.out.println(LocalDate.parse("2020-01-01").with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY)));
操作时间类LocalTime
LocalTime time=LocalTime.now();//取当前时间,默认带毫秒
time=LocalTime.now().withNano(0);//去除毫秒
time=LocalTime.now().plusHours(2);//2小时后的时间
time=LocalTime.now().plusMinutes(30);//30分钟后的时间
System.out.println(time);
操作日期时间类 LocalDateTime
与上面差不多,只是可以带日期和时间,不再赘述
Duration类用来获取两个LocalTime或LocalDateTime相差的时间
LocalTime time1 = LocalTime.now();
LocalTime time2 = LocalTime.now().plusHours(2).plusMinutes(30);
Duration duration = Duration.between(time1, time2);
System.out.println(duration.getSeconds());
Period类用来获取两个LocalDate相差的日期
LocalDate date1 = LocalDate.now();
LocalDate date2 = LocalDate.now().plusDays(3);
Period period = Period.between(date1, date2);
System.out.println(period.getDays());
获取指定时区的时间
ZonedDateTime time=ZonedDateTime.now();
System.out.println(time);
ZoneId zone = ZoneId.of("Europe/Paris");//美丽的巴黎
//获取指定的时区时间
ZonedDateTime paris = ZonedDateTime.now(zone);
System.out.println(paris);