日期处理
在Java8之前,操作日期的话不是很方便,有些地方需要自己编程实现。在Java8中的java.time包下新增很多关于日期处理的类,通过这些类可以使开发者更便捷的操作日期,这些类都是final修饰的,并且是线程安全的。
LocalDate类
LocalDate类只能操作日期相关的数据,不包含时间
//LocalDate 类
//LocalDate类只能操作和日期相关的数据不包含时间
LocalDate date1 = LocalDate.now();
System.out.println(date1); //2019-03-11
int year = date1.getYear();
int month = date1.getMonthValue();
int day = date1.getDayOfMonth();
//格式化日期
String s1 = date1.format(DateTimeFormatter.ofPattern("YYYY年MM月DD日"));
System.out.println(s1);
//判断闰年
boolean leap = date1.isLeapYear();
//获取该月份有 几天
int len = date1.lengthOfMonth();
System.out.println(len);
LocalTime类
LocalTime类只能操作时间相关的数据,不包含日期
LocalTime time1 = LocalTime.now().withNano(0);
System.out.println(time1);
//设置时间
LocalTime time2 = LocalTime.of(6, 30, 20);
System.out.println(time2);
LocalTime time3 = LocalTime.parse("18:20:20");
System.out.println(time3);
LocalDateTime类
LocalDateTime类可以处理日期和时间的数据
//LocalDateTime类
LocalDateTime time = LocalDateTime.now();
System.out.println("当前的时间为:"+time);
Duration和Period
Duration类用来 获取 两个 LocalTime相差的时间
Period类用来获取两个LocalDate相差的日期
//计算两个LocalTime相差的时间
LocalTime time7 = LocalTime.of(7, 20);
LocalTime time8 = LocalTime.of(7, 30);
Duration duration = Duration.between(time7, time8);
System.out.println("二者相差的时间秒数为:"+duration.getSeconds());
//计算祖国从建国道现在 过了多少年多少月多少日
//建国日期
LocalDate begin = LocalDate.of(1949, 10, 1);
//今天日期
LocalDate end = LocalDate.now();
System.out.println("祖国已经成立");
System.out.println(Period.between(begin, end).getYears()+"年");
System.out.println(Period.between(begin, end).getMonths()+"月");
System.out.println(Period.between(begin, end).getDays()+"日");