jdk8在java.time包中提供了很多可以操作的类。、
System.out.println("年份:" + date.getYear());
System.out.println("月份:" + date.getMonth().getValue());
System.out.println("月份:" + date.getMonthValue());
System.out.println("一个月中的第几天:" + date.getDayOfMonth());
System.out.println("一周中的第n天:n=" + date.getDayOfYear());
System.out.println("一周中的第n天:n=" + date.getDayOfWeek());
System.out.println("一个月的长度:" + date.lengthOfMonth());
System.out.println("一年的长度:" + date.lengthOfYear());
System.out.println("是否是闰年:" + date.isLeapYear());
// 获取日期二
LocalDate now = LocalDate.now();
// 获取日期三
// 也可以这样获取时间
int year = date.get(ChronoField.YEAR);
int month = date.get(ChronoField.MONTH_OF_YEAR);
int day = date.get(ChronoField.DAY_OF_MONTH);
LocalDateTime dt1 = LocalDateTime.of(2019, Month.MARCH, 18, 13, 45, 20);
LocalDate date = LocalDate.now();
LocalTime time = LocalTime.now();
LocalDateTime dt2 = LocalDateTime.of(date, time);
LocalDateTime dt3 = date.atTime(time);
LocalDateTime dt4 = date.atTime(12, 1);
LocalDateTime dt5 = date.atTime(12, 1, 6);
以上所有的类都实现了Temporal接口.它定义了如何读取和操作为时间建模的对象的值.
那么就很容易创建两个Temporal对象之间的duration.
// 注意不能计算两个LocalDate之间的时间间隔,更不能混用。
LocalDateTime now = LocalDateTime.now();
LocalDateTime pre = LocalDateTime.of(2019, 2, 22, 0, 0, 0);
Duration between = Duration.between(pre, now);
System.out.println(between.getSeconds());
有的时候,你需要进行一些更加复杂的操作,比如,将日期调整到下个周日、下个工作日,或者是本月的最后一天。
LocalDate now = LocalDate.now();
LocalDate date1 = now.with(TemporalAdjusters.nextOrSame(DayOfWeek.MONDAY));
System.out.println(date1);
LocalDate date2 = now.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
System.out.println(date2);
LocalDate now = LocalDate.now();
System.out.println(now.format(DateTimeFormatter.BASIC_ISO_DATE));
System.out.println(LocalDate.parse("2019-02-23", DateTimeFormatter.ISO_LOCAL_DATE));
// 创建自定义的格式器
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
System.out.println(now.format(dateTimeFormatter));
// 使用DateTimeFormatterBuild创建自己的格式器
DateTimeFormatter dateTimeFormatter1 = new DateTimeFormatterBuilder().appendText(ChronoField.DAY_OF_MONTH)
.appendLiteral(", ").toFormatter();
System.out.println(now.format(dateTimeFormatter1));
LocalDate now = LocalDate.now();
System.out.println(now.atStartOfDay(ZoneId.of("Asia/Shanghai")));
LocalDateTime now1 = LocalDateTime.now();
System.out.println("巴黎时间:" + now1.atZone(ZoneId.of("Europe/Paris")));
Instant now2 = Instant.now();
System.out.println(now2.atZone(ZoneId.of("Europe/Paris")));
如果你觉得写的还不错,就关注下公众号呗,关注后,有点小礼物回赠给你。
你可以获得5000+电子书,java,springCloud,adroid,python等各种视频教程,IT类经典书籍,各种软件的安装及破解教程。
希望一块学习,一块进步!