概述
日期时间API的迭代
- 第一代:jdk 1.0 Date类
- 第二代:jdk 1.1 Calendar类,一定程度上替换Date类
- 第三代:jdk 1.8 提出了新的一套API
前两代存在的问题
- 可变性:像日期和时间这样的类应该是不可变的。
- 偏移性:Date中的年份是从1900开始的,而月份都从0开始。
- 格式化:格式化只对Date用,Calendar则不行。
此外,它们也不是线程安全的;不能处理闰秒
//偏移量Date date1 = new Date(2020 - 1900,9 - 1,8);System.out.println(date1);//Tue Sep 08 00:00:00 GMT+08:00 2020
涉及到的包
java.time – 包含值对象的基础包
- java.time.chrono – 提供对不同的日历系统的访问
- java.time.format – 格式化和解析时间和日期
- java.time.temporal – 包括底层框架和扩展特性
- java.time.zone – 包含时区支持的类
LocalDate、LocalTime、LocalDateTime
说明
LocalDate、LocalTime、LocalDateTime 类是其中较重要的几个类,它们的实例是不可变的对象,分别表示使用 ISO-8601日历系统的日期、时间、日期和时间。 它们提供了简单的本地日期或时间,并不包含当前的时间信息,也不包含与时区相关的信息。
- LocalDate代表IOS格式(yyyy-MM-dd)的日期,可以存储生日、纪念日等日期。
- LocalTime表示一个时间,而不是日期。
LocalDateTime是用来表示日期和时间的,这是一个最常用的类之一。
常用方法
now() / now(ZoneId zone)静态方法,根据当前时间创建对象/指定时区的对象of()静态方法,根据指定日期/时间创建对象getDayOfMonth()/getDayOfYear()获得月份天数(1-31) /获得年份天数(1-366)getDayOfWeek()获得星期几(返回一个 DayOfWeek 枚举值)getMonth()获得月份, 返回一个 Month 枚举值getMonthValue() / getYear()获得月份(1-12) /获得年份getHour()/getMinute()/getSecond()获得当前对象对应的小时、分钟、秒withDayOfMonth()/withDayOfYear()/ withMonth()/withYear()将月份天数、年份天数、月份、年份修改为指定的值并返回新的对象plusDays(), plusWeeks(), plusMonths(), plusYears(),plusHours()向当前对象添加几天、几周、几个月、几年、几小时minusMonths() / minusWeeks()/ minusDays()/minusYears()/minusHours()从当前对象减去几月、几周、几天、几年、几小时
```java //now():获取当前的日期、时间、日期+时间 LocalDate localDate = LocalDate.now(); LocalTime localTime = LocalTime.now(); LocalDateTime localDateTime = LocalDateTime.now();System.out.println(localDate);//2022-03-16 System.out.println(localTime);//22:20:11.790 System.out.println(localDateTime);//2022-03-16T22:20:11.790
//of():设置指定的年、月、日、时、分、秒。没有偏移量 LocalDateTime localDateTime1 = LocalDateTime.of(2020, 10, 6, 13, 23, 43); System.out.println(localDateTime1);//2020-10-06T13:23:43
//getXxx():获取相关的属性System.out.println(localDateTime.getDayOfMonth());//16System.out.println(localDateTime.getDayOfWeek());//WEDNESDAYSystem.out.println(localDateTime.getMonth());//MARCHSystem.out.println(localDateTime.getMonthValue());//3System.out.println(localDateTime.getMinute());//20//体现不可变性//withXxx():设置相关的属性LocalDate localDate1 = localDate.withDayOfMonth(22);System.out.println(localDate);//2022-03-16System.out.println(localDate1);//2022-03-22LocalDateTime localDateTime2 = localDateTime.withHour(4);System.out.println(localDateTime);//2022-03-16T22:20:11.790System.out.println(localDateTime2);//2022-03-16T04:20:11.790//不可变性LocalDateTime localDateTime3 = localDateTime.plusMonths(3);System.out.println(localDateTime);//2022-03-16T22:20:11.790System.out.println(localDateTime3);//2022-06-16T22:20:11.790LocalDateTime localDateTime4 = localDateTime.minusDays(6);System.out.println(localDateTime);//2022-03-16T22:20:11.790System.out.println(localDateTime4);//2022-03-10T22:20:11.790
---<a name="zsmHq"></a># 时间点:Instant<a name="TKQrq"></a>### 说明① 时间线上的一个瞬时点。 概念上讲,它只是简单的表示自1970年1月1日0时0分0秒(UTC开始的秒数)<br />② 类似于 java.util.Date类<a name="QSNaM"></a>### 常用方法`now() `静态方法,返回默认UTC时区的Instant类的对象 <br />`ofEpochMilli(long epochMilli)` 静态方法,返回在1970-01-01 00:00:00基础上加上指定毫秒数之后的Instant类的对象 <br />`atOffset(ZoneOffset offset)` 结合即时的偏移来创建一个 <br />`OffsetDateTime toEpochMilli()` 返回1970-01-01 00:00:00到当前时间的毫秒数,即为时间戳```java//now():获取本初子午线对应的标准时间Instant instant = Instant.now();System.out.println(instant);//2019-02-18T07:29:41.719Z//添加时间的偏移量OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));System.out.println(offsetDateTime);//2019-02-18T15:32:50.611+08:00//toEpochMilli():获取自1970年1月1日0时0分0秒(UTC)开始的毫秒数 ---> Date类的getTime()long milli = instant.toEpochMilli();System.out.println(milli);//ofEpochMilli():通过给定的毫秒数,获取Instant实例 -->Date(long millis)Instant instant1 = Instant.ofEpochMilli(1550475314878L);System.out.println(instant1);
日期时间格式化类:DateTimeFormatter
说明
① 格式化或解析日期、时间
② 类似于SimpleDateFormat
实例化方式
预定义的标准格式。如:ISO_LOCAL_DATE_TIME; ISO_LOCAL_DATE; ISO_LOCAL_TIME
本地化相关的格式。如:ofLocalizedDateTime(FormatStyle.LONG)
自定义的格式。如:ofPattern(“yyyy-MM-dd hh:mm:ss”)
常用方法
- ofPattern(String pattern) 静态方法 , 返回一个指定字符串格式的DateTimeFormatter
- format(TemporalAccessor t) 格式化一个日期、时间,返回字符串
parse(CharSequence text) 将指定格式的字符序列解析为一个日期、时间
```java方式一:预定义的标准格式。如:ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIMEDateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;//格式化:日期-->字符串LocalDateTime localDateTime = LocalDateTime.now();String str1 = formatter.format(localDateTime);System.out.println(localDateTime);System.out.println(str1);//2019-02-18T15:42:18.797//解析:字符串 -->日期TemporalAccessor parse = formatter.parse("2019-02-18T15:42:18.797");System.out.println(parse);
// 方式二: // 本地化相关的格式。如:ofLocalizedDateTime() // FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT :适用于LocalDateTime DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG); //格式化 String str2 = formatter1.format(localDateTime); System.out.println(str2);//2019年2月18日 下午03时47分16秒
// 本地化相关的格式。如:ofLocalizedDate() // FormatStyle.FULL / FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT : 适用于LocalDate DateTimeFormatter formatter2 = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM); //格式化 String str3 = formatter2.format(LocalDate.now()); System.out.println(str3);//2019-2-18
// 重点: 方式三:自定义的格式。如:ofPattern(“yyyy-MM-dd hh:mm:ss”) DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern(“yyyy-MM-dd hh:mm:ss”); //格式化 String str4 = formatter3.format(LocalDateTime.now()); System.out.println(str4);//2019-02-18 03:52:09
//解析TemporalAccessor accessor = formatter3.parse("2019-02-18 03:52:09");System.out.println(accessor);
---<a name="IeWkd"></a># 其它API<a name="Kygt5"></a>### 带时区的日期时间:ZonedDateTime / ZoneId```java// ZoneId:类中包含了所的时区信息@Testpublic void test1(){//getAvailableZoneIds():获取所的ZoneIdSet<String> zoneIds = ZoneId.getAvailableZoneIds();for(String s : zoneIds){System.out.println(s);}System.out.println();//获取“Asia/Tokyo”时区对应的时间LocalDateTime localDateTime = LocalDateTime.now(ZoneId.of("Asia/Tokyo"));System.out.println(localDateTime);}//ZonedDateTime:带时区的日期时间@Testpublic void test2(){//now():获取本时区的ZonedDateTime对象ZonedDateTime zonedDateTime = ZonedDateTime.now();System.out.println(zonedDateTime);//now(ZoneId id):获取指定时区的ZonedDateTime对象ZonedDateTime zonedDateTime1 = ZonedDateTime.now(ZoneId.of("Asia/Tokyo"));System.out.println(zonedDateTime1);}
时间间隔:Duration—用于计算两个“时间”间隔,以秒和纳秒为基准

@Testpublic void test3(){LocalTime localTime = LocalTime.now();LocalTime localTime1 = LocalTime.of(15, 23, 32);//between():静态方法,返回Duration对象,表示两个时间的间隔Duration duration = Duration.between(localTime1, localTime);System.out.println(duration);System.out.println(duration.getSeconds());System.out.println(duration.getNano());LocalDateTime localDateTime = LocalDateTime.of(2016, 6, 12, 15, 23, 32);LocalDateTime localDateTime1 = LocalDateTime.of(2017, 6, 12, 15, 23, 32);Duration duration1 = Duration.between(localDateTime1, localDateTime);System.out.println(duration1.toDays());}
日期间隔:Period —用于计算两个“日期”间隔,以年、月、日衡量

@Testpublic void test4(){LocalDate localDate = LocalDate.now();LocalDate localDate1 = LocalDate.of(2028, 3, 18);Period period = Period.between(localDate, localDate1);System.out.println(period);System.out.println(period.getYears());System.out.println(period.getMonths());System.out.println(period.getDays());Period period1 = period.withYears(2);System.out.println(period1);}
日期时间校正器:TemporalAdjuster
@Testpublic void test5(){//获取当前日期的下一个周日是哪天?TemporalAdjuster temporalAdjuster = TemporalAdjusters.next(DayOfWeek.SUNDAY);LocalDateTime localDateTime = LocalDateTime.now().with(temporalAdjuster);System.out.println(localDateTime);//获取下一个工作日是哪天?LocalDate localDate = LocalDate.now().with(new TemporalAdjuster(){@Overridepublic Temporal adjustInto(Temporal temporal) {LocalDate date = (LocalDate)temporal;if(date.getDayOfWeek().equals(DayOfWeek.FRIDAY)){return date.plusDays(3);}else if(date.getDayOfWeek().equals(DayOfWeek.SATURDAY)){return date.plusDays(2);}else{return date.plusDays(1);}}});System.out.println("下一个工作日是:" + localDate);}
