JDK1.8引入时间工具
Java8新增了date和time的util包,用于替换原先的时间工具。Java处理日期、日历和时间的方式一直为社区所诟病,将 java.util.Date设定为可变类型,以及SimpleDateFormat的非线程安全使其应用非常受限。
新API基于ISO标准日历系统,java.time包下的所有类都是不可变类型而且线程安全。
- java.time.chrono 年表包:里面包含很多年表,包括日本年表、泰国年表、民国、伊斯兰历等。
- java.time.format 格式化包:格式化和解析时间和日期,主要类是DateTimeFormatter
- java.time.temPoral 时态包:包含了时态的一些操作定义、底层框架和扩展特性,如提供细粒度的时间控制field、unit,如weeks、months、month-of-year等
- java.time.zone 时区包:包含了时区的一些支持类
常用方法
@Test
public void doTime() {
//当前时间
LocalDate today = LocalDate.now();
System.out.println("当前日期方法 LocalDate.now() : " + today);
LocalTime time = LocalTime.now();
System.out.println("当前时间方法 LocalTime.now() : " + time);
LocalDateTime dateTime = LocalDateTime.now(Clock.system(ZoneId.systemDefault()));
System.out.println("当前完整日期 : " + dateTime);
int year = today.getYear();
int month = today.getMonthValue();
int day = today.getDayOfMonth();
System.out.printf("Year : %d Month : %d day : %d \t %n", year, month, day);
//指定某一天
LocalDate dateOfBirth = LocalDate.of(1990, 03, 22);
System.out.println("My Date of birth is : " + dateOfBirth);
LocalDate date1 = LocalDate.of(2021, 04, 20);
if(date1.equals(today)){
System.out.printf("Today %s and date1 %s are same date %n", today, date1);
}
//时间格式化
System.out.println(dateTime.format(DateTimeFormatter.ISO_LOCAL_DATE));
System.out.println(dateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
System.out.println(dateTime.format(DateTimeFormatter.ISO_LOCAL_TIME));
System.out.println(dateTime.format(DateTimeFormatter.BASIC_ISO_DATE));
System.out.println(dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH🇲🇲ss")));
System.out.println(dateTime.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)));
System.out.println(dateTime.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)));
System.out.println(dateTime.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.valueOf("MEDIUM"))));
System.out.println(LocalDateTime.parse("2021-04-20T10:15:30").toString());
System.out.println(LocalDate.parse("2021-04-20",DateTimeFormatter.ISO_LOCAL_DATE));
System.out.println(LocalTime.parse("22:15:30",DateTimeFormatter.ISO_LOCAL_TIME));
//时间加减法
//时区偏移量
LocalDateTime datetime = LocalDateTime.of(2021, Month.JANUARY, 20, 21, 30);
ZoneOffset offset = ZoneOffset.of("+08:00");
OffsetDateTime date = OffsetDateTime.of(datetime, offset);
System.out.println("Date and Time with timezone offset in Java : " + date);
//两个时间相隔多久
LocalDate java8Release = LocalDate.of(2014, Month.MARCH, 14);
Period periodToNextJavaRelease = Period.between(today, java8Release);
System.out.println("Months left between today and Java 8 release : " + periodToNextJavaRelease.getMonths() );
}
感谢Leolu007的分享 https://blog.csdn.net/leolu007/article/details/53112363