文章目录

  • Java 8 日期和时间
    • 为什么Java8提供了新的日期与时间的API?
    • 简单概述
    • Instant类
      • Instant与Date的转换
      • 将字符串类型的Instant转换为Instantd对象
      • Instant的加減操作
      • Instant时间差计算
      • Instant时间大小比较
      • Instant详解
      • Instant.now()转化为北京时间
    • LocalDate类
      • 创建LocalDate的方式
      • LocalDate获取日,月,年
      • LocalDate的加减操作
      • LocalDate 与 Date的转换
      • LocalDate 与 Instant的转换
      • LocalDate 详解
    • LocalTime类
      • 创建LocalTime的方式
      • LocalTime 获取时,分,秒
      • LocalTime的加减操作
      • LocalTime 与 Date的转换
      • LocalTime 与 Instant的转换
      • LocalTime 详解
    • LocalDateTime类
      • LocalDateTime的创建方式
      • LocalDateTime获取年,月,日,小时,分钟或秒
      • LocalDateTime的加减操作
      • LocalDateTime 与 Date的转换
      • LocalDateTime 与 Instant的转换
    • Period类
      • 创建Period的方式
      • Period获取某个期间的年/月/日组件
      • Period的加减操作
      • 年龄计算器
    • ZonedDateTime类
      • ZonedDateTime 创建方式
      • ZonedDateTime 的加减操作
    • Duration 类
      • Duration 的创建方式
    • DateTimeFormatter 类
    • 参考
    • 源代码

Java 8 日期和时间

为什么Java8提供了新的日期与时间的API?

官方是这么解释的:

Why do we need a new date and time library?

A long-standing bugbear of Java developers has been the inadequate support for the date and time use cases of ordinary developers.

For example, the existing classes (such as java.util.Date and SimpleDateFormatter) aren’t thread-safe, leading to potential concurrency issues for users—not something the average developer would expect to deal with when writing date-handling code.

Some of the date and time classes also exhibit quite poor API design. For example, years in java.util.Date start at 1900, months start at 1, and days start at 0—not very intuitive.

These issues, and several others, have led to the popularity of third-party date and time libraries, such as Joda-Time.

In order to address these problems and provide better support in the JDK core, a new date and time API, which is free of these problems, has been designed for Java SE 8.

The project has been led jointly by the author of Joda-Time (Stephen Colebourne) and Oracle, under JSR 310, and will appear in the new Java SE 8 package java.time.

参考链接:官方文档

总的来说就是以前写的Date API不好用,而且存在一些线程安全问题,给开发人员造成很多的烦恼,以至于开发人员需要使用其他优秀第三方的日期API,比如Joda-Time。Oracle可能实在忍不了,所以根据Joda-Time API中的一些优秀设计,设计了Java8的Date和Time,放在了新的包下java.time

简单概述

  • java.time包中,Instant类表示时间线上的一个点,通常用于对时间进行操作。 LocalDate类为没有时间和时区部分的日期,例如:2021-02-24
    如果你需要日期和时间,就选择LocalDateTime,例如:2021-02-24T13:49:10.758276300
    如果你需要一段时间但不关心日期,那么可以使用LocalTime,例如:13:50:26.058539700
    如果时区很重要,日期和时间API提供ZonedDateTime类。 顾名思义,这个类表示带有时区日期时间。

  • 然后有两个类来测量时间总计,即Duration类和Period类。 这两个类是相似的,除了Duration是基于时间,但而Period是基于日期的。 Duration提供了纳秒精度的时间量。 例如,可以模拟飞行时间,因为它通常以小时数和分钟数表示。 另一方面,如果只关心天数,月数或年数,例如计算一个人的年龄,则Period更为适用。

  • java.time包也带有两个枚举DayOfWeekMonthDayOfWeek表示从一周的一天,从周一开始到周日。 Month枚举代表这一年的十二个月,从1月到12月。

  • 处理日期和时间通常涉及解析和格式。 日期和时间API通过在所有主要类中提供parseformat方法来解决这两个问题。 另外,java.time.format包含一个用于格式化日期和时间的DateTimeFormatter类。

参考:Java 8 Date-Time API 详解

Instant类

Instant 没有时区信息(也可以认为是0时区,即GMT时区),Instant实例表示时间线上的一个点。 参考点是标准的Java纪元(epoch),即1970-01-01T00:00:00Z1970年1月1日00:00 GMT)。

Instant的静态now方法返回一个表示当前时间的Instant对象。
getEpochSecond方法返回自纪元以来经过的秒数。 getNano方法返回自上一秒开始以来的纳秒数。

Instant类的一个常用用途是用来操作时间。

    @Testvoid testTime1() throws InterruptedException {Instant start = Instant.now();// do something hereTimeUnit.MILLISECONDS.sleep(100);Instant end = Instant.now();System.out.println(Duration.between(start, end).toMillis());}

如上面代码所示,Duration类用于返回两个Instant之间时间数量的差异。

Instant与Date的转换

Instant相当于Date

     @Testvoid testTime2() {//instant 相当于 dateInstant instant = Instant.now();System.out.println(instant); //2021-02-24T06:53:58.933542200ZDate date = new Date();System.out.println(date); //Wed Feb 24 14:53:58 CST 2021//instant转date 类方法(java.util.date)Date from = Date.from(instant);System.out.println(from); // Wed Feb 24 14:53:58 CST 2021//date 转instant 对象方法(java.util.date)Instant instant1 = date.toInstant();System.out.println(instant1); //2021-02-24T06:53:58.944Z//instant 根据毫秒值或者date转换为instant 类方法 (java.time)Instant instant2 = Instant.ofEpochMilli(date.getTime());System.out.println(instant2); //2021-02-24T06:53:58.944Z}

将字符串类型的Instant转换为Instantd对象

注意:必须传入的是符合 UTC格式的字符串

    @Testvoid testTime3() {Instant parse = Instant.parse("2021-02-24T08:59:10.142029600Z");System.out.println(parse);//2021-02-24T08:59:10.142029600Z}

Instant的加減操作

    @Testvoid testTime4() {//instant 在现有的instant的时间上追加些时间,下面例子追加了5小时10分钟,这里plus会产生新的instant对象Instant instant = Instant.now();Instant plus = instant.plus(Duration.ofHours(5).plusMinutes(10));System.out.println("instant:" + instant + ", plus:" + plus);//instant:2021-02-26T05:30:55.385967500Z, plus:2021-02-26T10:40:55.385967500ZSystem.out.println(instant == plus);//plus会产生新的instant对象 所以结果位false//instant 获取其5天前的instant(此刻)Instant minus = instant.minus(5, ChronoUnit.HOURS);System.out.println("instant:" + instant + ", minus:" + minus);//instant:2021-02-26T05:30:55.385967500Z, minus:2021-02-26T00:30:55.385967500Z//也可以直接调用相关减法方法,效果跟上面的方法一样Instant minus1 = instant.minusSeconds(60 * 60 * 5);System.out.println("instant:" + instant + ", minus1:" + minus1);//instant:2021-02-26T05:30:55.385967500Z, minus1:2021-02-26T00:30:55.385967500Z//减法方法,效果跟上面的方法一样Instant minus2 = instant.minus(Duration.ofHours(5));System.out.println("instant:" + instant + ", minus2:" + minus2);//instant:2021-02-26T05:30:55.385967500Z, minus2:2021-02-26T00:30:55.385967500Z}

Instant时间差计算

    @Testvoid testTime5() throws InterruptedException {//计算两个Instant之间的秒数, ChronoUnit用的什么,得到的结果就是什么单位Instant instant = Instant.now();TimeUnit.SECONDS.sleep(2);Instant instant2 = Instant.now();long between = ChronoUnit.SECONDS.between(instant, instant2);long between2 = Duration.between(instant, instant2).toSeconds();System.out.println(between);//2System.out.println(between2);//2}

Instant时间大小比较

    @Testvoid testTime6() throws InterruptedException {Instant instant = Instant.now();TimeUnit.SECONDS.sleep(2);Instant instant2 = Instant.now();//比较两个instant 相等 0, 前者时间纳秒值大于后者 1,小于后者 -1或小于0int i = instant.compareTo(instant2);System.out.println(i);//-1//判断instant时间前后,前者在后者之后返回true,反之falseboolean after = instant.isAfter(instant2);System.out.println(after);//false//判断instant时间前后,前者在后者之前返回true,反之false,正好与上面相反boolean before = instant.isBefore(instant2);System.out.println(before);//true}

Instant详解

通过Instant.now()获得的时间戳与北京时间相差八个小时,这是因为Instant.now()使用的是UTC时间,如果要转化为北京时间需要加上八个小时

/*** Obtains the current instant from the system clock.* <p>* This will query the {@link Clock#systemUTC() system UTC clock} to* obtain the current instant.* <p>* Using this method will prevent the ability to use an alternate time-source for* testing because the clock is effectively hard-coded.** @return the current instant using the system clock, not null*/public static Instant now() {return Clock.systemUTC().instant();}

而。LocalDateLocalDateTimenow()方法使用的是系统默认时区 不存在Instant.now()的时间问题。

Instant.now()转化为北京时间

    @Testvoid testTime7() {Instant now = Instant.now().plusMillis(TimeUnit.HOURS.toMillis(8));System.out.println("now:"+now);//now:2021-02-26T13:51:40.324904700Z}

LocalDate类

方法 描述
now 静态方法,返回今天的日期
of 从指定年份,月份和日期创建LocalDate的静态方法
getDayOfMonth, getMonthValue, getYear 以int形式返回此LocalDate的日,月或年
getMonth 以Month枚举常量返回此LocalDate的月份
plusDays, minusDays 给LocalDate添加或减去指定的天数
plusWeeks, minusWeeks 给LocalDate添加或减去指定的星期数
plusMonths, minusMonths 给LocalDate添加或减去指定的月份数
plusYears, minusYears 给LocalDate添加或减去指定的年数
isLeapYear 检查LocalDate指定的年份是否为闰年
isAfter, isBefore 检查此LocalDate是在给定日期之后还是之前
lengthOfMonth 返回此LocalDate中月份的天数
withDayOfMonth 返回此LocalDate的拷贝,将月份中的某天设置为给定值
withMonth 返回此LocalDate的拷贝,其月份设置为给定值
withYear 返回此LocalDate的拷贝,并将年份设置为给定值

创建LocalDate的方式

LocalDate提供了许多创建日期的方法。

    @Testvoid testLocalDate1() {LocalDate localDate = LocalDate.now();System.out.println(localDate);//2021-02-26LocalDate date = LocalDate.of(2018, 3, 7);System.out.println(date);//2018-03-07LocalDate date2 = LocalDate.of(2018, Month.MARCH, 7);System.out.println(date2);//2018-03-07}

LocalDate获取日,月,年

    @Testvoid testLocalDate2() {//LocalDate的日,月或年的方法,例如getDayOfMonth,getMonth,getMonthValue和getYear。他们都没有任何参数,并返回一个int或Month的枚举常量。LocalDate localDate = LocalDate.now();System.out.println(localDate.getDayOfYear());//61System.out.println(localDate.getDayOfMonth());//2Month month = localDate.getMonth(); //Month的枚举常量。System.out.println(month);//MARCHSystem.out.println(localDate.getYear());//2021System.out.println(localDate.getMonthValue());//2//get方法,接受一个TemporalField并返回这个LocalDate的一部分。 例如,传递ChronoField.YEAR以获取LocalDate的年份部分。//ChronoField是一个实现TemporalField接口的枚举int year = localDate.get(ChronoField.YEAR);System.out.println(year);//2021}

LocalDate的加减操作

    @Testvoid testLocalDate3() {LocalDate now = LocalDate.now();System.out.println(now);//2021-03-02LocalDate plusDays = now.plusDays(1);System.out.println(plusDays); //2021-03-03LocalDate minusDays = now.minusDays(1);System.out.println(minusDays);//2021-03-01LocalDate pastDate = now.minus(2, ChronoUnit.DECADES);System.out.println(pastDate);//2001-03-02LocalDate plus = now.plus(2, ChronoUnit.DAYS);System.out.println(plus);//2021-03-04//注意:LocalDate是不可变的,因此无法更改。 任何返回LocalDate的方法都返回LocalDate的新实例。}

LocalDate 与 Date的转换

    @Testvoid testLocalDate4() {Date date = new Date();Instant instant = date.toInstant();ZoneId zoneId = ZoneId.systemDefault();System.out.println(zoneId);//Asia/ShanghaiLocalDate localDate = LocalDate.ofInstant(instant, zoneId);System.out.println(localDate); //2021-03-03LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zoneId);LocalDate localDate2 = localDateTime.toLocalDate();System.out.println(localDate2);//2021-03-03}
    @Testvoid testLocalDate5() {// LocalDate 转 DateLocalDate localDate = LocalDate.now();ZoneId zone = ZoneId.systemDefault();Instant instant = localDate.atStartOfDay().atZone(zone).toInstant();Date date = Date.from(instant);System.out.println(date);//Wed Mar 03 00:00:00 CST 2021}

LocalDate 与 Instant的转换

    @Testvoid testLocalDate6() {//Instant 转 LocalDateZoneId zoneId = ZoneId.systemDefault();System.out.println(zoneId);//Asia/ShanghaiInstant now = Instant.now();System.out.println(now);//2021-03-03T12:31:29.568519200ZLocalDate localDate = LocalDate.ofInstant(now, zoneId);System.out.println(localDate);//2021-03-03}
   @Testvoid testLocalDate7() {//LocalDate 转 InstantZoneId zone = ZoneId.systemDefault();LocalDate now = LocalDate.now();System.out.println(now);//2021-03-03Instant instant = LocalDate.now().atStartOfDay().atZone(zone).toInstant();System.out.println(instant);//2021-03-02T16:00:00Z}

LocalDate 详解

当我们调用LocalDate.now()的时候我们会返回系统当前时区的一个日期, 从源码中就可以看出来

//-----------------------------------------------------------------------/*** Obtains the current date from the system clock in the default time-zone.* <p>* This will query the {@link Clock#systemDefaultZone() system clock} in the default* time-zone to obtain the current date.* <p>* Using this method will prevent the ability to use an alternate clock for testing* because the clock is hard-coded.** @return the current date using the system clock and default time-zone, not null*/public static LocalDate now() {return now(Clock.systemDefaultZone());}

LocalTime类

创建LocalTime的方式

     @Testvoid testLocalTime1() {LocalTime localTime = LocalTime.now();System.out.println(localTime);LocalTime time = LocalTime.of(1, 30, 20);System.out.println(time);//01:30:20}

LocalTime 获取时,分,秒

    @Testvoid testLocalTime2() {LocalTime localTime = LocalTime.now();System.out.println(localTime);//21:18:19.843617500int hour = localTime.getHour();int minute = localTime.getMinute();int second = localTime.getSecond();System.out.println(hour);//21System.out.println(minute);//18System.out.println(second);//19}

LocalTime的加减操作

    @Testvoid testLocalTime3() {LocalTime localTime = LocalTime.now();System.out.println(localTime);//21:26:15.524736600System.out.println(localTime.plus(1, ChronoUnit.HOURS));//22:26:15.524736600System.out.println(localTime.plusHours(1));//22:26:15.524736600System.out.println(localTime.plusMinutes(2));//21:28:15.524736600System.out.println(localTime.minus(1,ChronoUnit.HOURS));//20:26:15.524736600System.out.println(localTime.minusSeconds(1));//21:26:14.524736600}

LocalTime 与 Date的转换

    @Testvoid testLocalTime4(){//Date 转 LocalTimeDate date = new Date();System.out.println(date);//Thu Mar 04 19:53:57 CST 2021Instant instant = date.toInstant();ZoneId zone = ZoneId.systemDefault();LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);LocalTime localTime = localDateTime.toLocalTime();System.out.println(localTime);//19:53:57.089}
    @Testvoid testLocalTime5() {//LocalTime 转 DateLocalTime localTime = LocalTime.now();LocalDate localDate = LocalDate.now();LocalDateTime localDateTime = LocalDateTime.of(localDate, localTime);System.out.println(localTime);//19:55:14.254197800ZoneId zone = ZoneId.systemDefault();Instant instant = localDateTime.atZone(zone).toInstant();java.util.Date date = Date.from(instant);System.out.println(date);//Thu Mar 04 19:55:14 CST 2021}

LocalTime 与 Instant的转换

    @Testvoid testLocalTime6() {//Instant 转 LocalTimeInstant instant = Instant.now();System.out.println(instant);//2021-03-04T12:30:28.125689400ZZoneId zone = ZoneId.systemDefault();LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);LocalTime localTime = localDateTime.toLocalTime();System.out.println(localTime);//20:30:28.125689400}
    @Testvoid testLocalTime7() {//LocalTime 转 InstantLocalTime localTime = LocalTime.now();LocalDate localDate = LocalDate.now();LocalDateTime localDateTime = LocalDateTime.of(localDate, localTime);System.out.println(localTime);//19:55:14.254197800ZoneId zone = ZoneId.systemDefault();Instant instant = localDateTime.atZone(zone).toInstant();System.out.println(instant);//2021-03-04T12:30:48.286638100Z}

LocalTime 详解

当我们调用LocalTime.now()的时候我们会返回系统当前时区的一个时间, 从源码中就可以看出来

  //-----------------------------------------------------------------------/*** Obtains the current time from the system clock in the default time-zone.* <p>* This will query the {@link Clock#systemDefaultZone() system clock} in the default* time-zone to obtain the current time.* <p>* Using this method will prevent the ability to use an alternate clock for testing* because the clock is hard-coded.** @return the current time using the system clock and default time-zone, not null*/public static LocalTime now() {return now(Clock.systemDefaultZone());}

LocalDateTime类

LocalDateTime类是一个没有时区的日期时间的构建。 下表显示了LocalDateTime中一些重要的方法。 这些方法类似于LocalDate的方法,以及用于修改时间部分的一些其他方法,例如在LocalDate中不可用的plusHoursplusMinutesplusSeconds

方法 描述
now 返回当前日期和时间的静态方法。
of 从指定年份,月份,日期,小时,分钟,秒和毫秒创建LocalDateTime的静态方法。
getYear, getMonthValue, getDayOfMonth, getHour, getMinute, getSecond 以int形式返回此LocalDateTime的年,月,日,小时,分钟或秒部分。
plusDays, minusDays 给当前LocalDateTime添加或减去指定的天数。
plusWeeks, minusWeeks 给当前LocalDateTime添加或减去指定的周数。
plusMonths, minusMonths 给当前LocalDateTime添加或减去指定的月数。
plusYears, minusYears 给当前LocalDateTime添加或减去指定的年数。
plusHours, minusHours 给当前LocalDateTime添加或减去指定的小时数
plusMinutes, minusMinutes 给当前LocalDateTime添加或减去指定的分钟数
plusSeconds, minusSeconds 给当前LocalDateTime添加或减去指定的秒数
IsAfter, isBefore 检查此LocalDateTime是否在指定的日期时间之后或之前
withDayOfMonth 返回此LocalDateTime的拷贝,并将月份中的某天设置为指定值
withMonth, withYear 返回此LocalDateTime的拷贝,其月或年设置为指定值

withHour, withMinute, withSecond 返回此LocalDateTime的拷贝,其小时/分钟/秒设置为指定值

LocalDateTime的创建方式

    @Testvoid testLocalDateTime1() {LocalDateTime localDateTime = LocalDateTime.now();System.out.println(localDateTime);//2021-03-04T21:10:08.697760700LocalDateTime dateTime = LocalDateTime.of(2021, 3, 14, 5, 20);System.out.println(dateTime);//2021-03-14T05:20}

LocalDateTime获取年,月,日,小时,分钟或秒

    @Testvoid testLocalDateTime2() {LocalDateTime dateTime = LocalDateTime.of(2021, 3, 14, 5, 20);System.out.println(dateTime);//2021-03-14T05:20System.out.println(dateTime.getYear());//2021System.out.println(dateTime.getMonthValue());//3System.out.println(dateTime.getHour());//5System.out.println(dateTime.getMinute());//20System.out.println(dateTime.getSecond());//0}

LocalDateTime的加减操作

    @Testvoid testLocalDateTime3() {LocalDateTime dateTime = LocalDateTime.of(2021, 3, 14, 5, 20);System.out.println(dateTime);//2021-03-14T05:20System.out.println(dateTime.plusDays(1).plusMinutes(1).plusMonths(1).plus(1,ChronoUnit.SECONDS));//2021-04-15T05:21:01System.out.println(dateTime.minus(1, ChronoUnit.DAYS).minusSeconds(1).minusHours(1).minusMonths(1));//2021-02-13T04:19:59}

LocalDateTime 与 Date的转换

    @Testvoid testLocalDateTime4() {// LocalDateTime 转 DateLocalDateTime localDateTime = LocalDateTime.now();System.out.println(localDateTime); //2021-03-04T23:35:28.661442800ZoneId zone = ZoneId.systemDefault();Instant instant = localDateTime.atZone(zone).toInstant();java.util.Date date = Date.from(instant);System.out.println(date);//Thu Mar 04 23:35:28 CST 2021}
    @Testvoid testLocalDateTime5() {// Date 转 LocalDateTimejava.util.Date date = new java.util.Date();System.out.println(date); //Thu Mar 04 23:36:23 CST 2021Instant instant = date.toInstant();ZoneId zone = ZoneId.systemDefault();LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);System.out.println(localDateTime);//2021-03-04T23:36:23.589}

LocalDateTime 与 Instant的转换

    @Testvoid testLocalDateTime6() {// LocalDateTime 转 InstantLocalDateTime localDateTime = LocalDateTime.now();System.out.println(localDateTime); //2021-03-07T16:23:30.639903200ZoneId zone = ZoneId.systemDefault();Instant instant = localDateTime.atZone(zone).toInstant();System.out.println(instant);//2021-03-07T08:23:30.639903200Z}
    @Testvoid testLocalDateTime7() {// Instant 转 LocalDateTimeInstant instant = Instant.now();System.out.println(instant); //2021-03-07T08:23:43.286203600ZZoneId zone = ZoneId.systemDefault();LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);System.out.println(localDateTime);//2021-03-07T16:23:43.286203600}

Period类

方法 描述
between 在两个LocalDates之间创建一个Period示例
ofDays, ofWeeks, ofMonths, ofYears 创建代表给定天数/周/月/年的Period实例
of 根据给定的年数,月数和天数创建一个Period实例
getDays, getMonths, getYears 以int形式返回此Period的天数/月/年
isNegative 如果此Period的三个部分中的任何一个为负数,则返回true。 否则返回false
isZero 如果此Period的所有三个部分均为零,则返回true。 否则,返回false
plusDays, minusDays 在此Period上添加或减去给定的天数
plusMonths, minusMonths 在此Period上增加或减去给定的月数
plusYears, minusYears 在此Period增加或减去给定的年数
withDays 以指定的天数返回此Period的拷贝
withMonths 以指定的月数返回此Period的拷贝
withYears 以指定的年数返回此Period的拷贝

创建Period的方式

创建一个Period很简单,between,of,ofDays / ofWeeks / ofMonths / ofYears等静态工厂方法可以很简单帮我们创建Period

    @Testvoid testPeriodTest1() {//创建代表两周的Period实例Period twoWeeks = Period.ofWeeks(2);System.out.println(twoWeeks);//P14D//创建代表一年两个月三天的Period实例Period p = Period.of(1, 2, 3);System.out.println(p);//P1Y2M3D}

Period获取某个期间的年/月/日组件

    @Testvoid testPeriodTest2() {//创建代表两周的Period实例Period twoWeeks = Period.ofWeeks(2);System.out.println(twoWeeks);//P14DSystem.out.println(twoWeeks.getDays());//14Period twoYears = Period.ofYears(2);System.out.println(twoYears);//P2YSystem.out.println(twoYears.getYears());//2Period twoMonths = Period.ofMonths(2);System.out.println(twoMonths);//P2MSystem.out.println(twoMonths.getMonths());//2}

Period的加减操作

    @Testvoid testPeriodTest3() {//创建代表两周的Period实例Period twoWeeks = Period.ofWeeks(2);System.out.println(twoWeeks);//P14DSystem.out.println(twoWeeks.getDays());//14Period plusDays = twoWeeks.plusDays(1);System.out.println(plusDays.getDays());//15Period minusDays = plusDays.minusDays(2);System.out.println(minusDays.getDays());//13}

年龄计算器

    @Testvoid testPeriodTest4() {LocalDate dateA = LocalDate.of(1978, 8, 26);LocalDate dateB = LocalDate.of(1988, 9, 28);Period period = Period.between(dateA, dateB);System.out.printf("Between %s and %s"+ " there are %d years, %d months"+ " and %d days%n", dateA, dateB,period.getYears(),period.getMonths(),period.getDays());//Between 1978-08-26 and 1988-09-28 there are 10 years, 1 months and 2 days}

ZonedDateTime类

ZonedDateTime类以一个时区为日期时间的构建。

ZonedDateTime始终是不可变的,时间分量的存储精度为纳秒。

ZonedDateTIme中一些重要方法的使用与LocalDateTime类似,只是多了一个时区的概念。

ZonedDateTime 创建方式

    @Testvoid testZonedDateTime1() {//无参now方法会使用计算机的默认时区创建ZonedDateTimeZonedDateTime zonedDateTime = ZonedDateTime.now();System.out.println(zonedDateTime);//2021-03-07T20:56:15.409935300+08:00[Asia/Shanghai]//允许传递区域标识符ZonedDateTime parisTime = ZonedDateTime.now(ZoneId.of("Europe/Paris"));System.out.println(parisTime);//2021-03-07T13:56:15.411934400+01:00[Europe/Paris]ZonedDateTime time = ZonedDateTime.of(2021, 3, 4, 2, 2, 2, 2, ZoneId.systemDefault());System.out.println(time);//2021-03-04T02:02:02.000000002+08:00[Asia/Shanghai]ZonedDateTime dateTime = ZonedDateTime.of(LocalDateTime.now(), ZoneId.of("Europe/Paris"));System.out.println(dateTime);//2021-03-07T20:56:15.414933100+01:00[Europe/Paris]ZonedDateTime zonedDateTime1 = ZonedDateTime.of(LocalDate.now(), LocalTime.now(), ZoneId.of("Europe/Paris"));System.out.println(zonedDateTime1);//2021-03-07T20:56:15.414933100+01:00[Europe/Paris]}

查看所有的时区:

    @Testvoid testZonedDateTimeTest2() {Set<String> availableZoneIds = ZoneId.getAvailableZoneIds();for (String availableZoneId : availableZoneIds) {System.out.println(availableZoneId);}}

ZonedDateTime 的加减操作

    @Testvoid testZonedDateTime3() {ZonedDateTime zonedDateTime = ZonedDateTime.now();System.out.println(zonedDateTime);//2021-03-07T21:00:39.707036800+08:00[Asia/Shanghai]System.out.println(zonedDateTime.plusDays(1));//2021-03-08T21:00:39.707036800+08:00[Asia/Shanghai]System.out.println(zonedDateTime.minus(1, ChronoUnit.DAYS));//2021-03-06T21:00:39.707036800+08:00[Asia/Shanghai]}

Duration 类

Duration类是基于时间的持续时间的构建。 它与Period类似,不同之处在于Duration的时间分量为纳秒精度,并考虑了ZonedDateTime实例之间的时区.

方法 描述
between 在两个时差的对象之间创建一个Duration实例,例如在两个LocalDateTime或两个ZonedDateTime之间。
ofYears, ofMonths, ofWeeks, ofDays, ofHours, ofMinutes, ofSeconds, ofNano 创建给定年数/月/周/天/小时/分钟/秒/纳秒的Duration实例
of 根据指定数量的时间单位创建Duration实例
toDays, toHours, toMinutes 以int形式返回此Duration的天数/小时/分钟数
isNegative 如果此Duration为负,则返回true。 否则返回false。
isZero 如果此Duration长度为零,则返回true。 否则,返回false
plusDays, minusDays 在此Duration内添加或减去指定的天数。
plusMonths, minusMonths 在此Duration内添加或减去指定的月数。
plusYears, minusYears 在Duration内添加或减去指定的年数
withSeconds 以指定的秒数返回此Duration的拷贝。

Duration 的创建方式

可以通过调用静态方法between或of来创建Duration

    @Testvoid testDuration1() {LocalDateTime dateTimeA = LocalDateTime.of(2015, 1, 26, 8, 10, 0, 0);LocalDateTime dateTimeB = LocalDateTime.of(2015, 1, 26, 11, 40, 0, 0);Duration duration = Duration.between(dateTimeA, dateTimeB);System.out.printf("There are %d hours and %d minutes.%n",duration.toHours(),duration.toMinutes() % 60);//There are 3 hours and 30 minutes.}

两个ZoneDateTime之间创建一个Duration,具有相同的日期和时间,但时区不同。

    @Testvoid testDuration2() {//相同时间 不同时区ZonedDateTime zdt1 = ZonedDateTime.of(LocalDateTime.of(2015, Month.JANUARY, 1,8, 0),ZoneId.of("America/Denver"));ZonedDateTime zdt2 = ZonedDateTime.of(LocalDateTime.of(2015, Month.JANUARY, 1,8, 0),ZoneId.of("America/Toronto"));Duration duration = Duration.between(zdt1, zdt2);System.out.printf("There are %d hours and %d minutes.%n",duration.toHours(),duration.toMinutes() % 60);//There are -2 hours and 0 minutes.}

DateTimeFormatter 类

    @Testvoid testDateTimeFormatter() {LocalDate localDate = LocalDate.of(2019, 9, 10);String format = localDate.format(DateTimeFormatter.BASIC_ISO_DATE);System.out.println(format);//20190910DateTimeFormatter dateTimeFormatter =   DateTimeFormatter.ofPattern("dd/MM/yyyy");String format2 = localDate.format(dateTimeFormatter);System.out.println(format2);//10/09/2019DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.CHINA);LocalDateTime parse = LocalDateTime.parse("2017-04-01 22:39:40", timeFormatter);System.out.println(parse);//2017-04-01T22:39:40}

参考

java 8新特性 instant 和 LocalDateTime

使用Java 8 的日期和时间Api

LocalDateTime,String,Instant相互转换

Java8学习笔记:LocalDateTime、Instant 和 OffsetDateTime 相互转换

java中的时间与时区:LocalDateTime和Date

Java 8 Date-Time API 详解

Java面试问题总结——为什么处理时间问题建议使用LocalDate类而逐渐抛弃Date类?

源代码

https://gitee.com/cckevincyh/java8_time_date

Java 8 日期和时间相关推荐

  1. Java 8 日期和时间解读

    转载自 Java 8 日期和时间解读 现在,一些应用程序仍然在使用java.util.Date和java.util.Calendar API和它们的类库,来使我们在生活中更加轻松的处理日期和时间,比如 ...

  2. java国际化——日期和时间+排序

    [0]README 1) 本文部分文字描述转自 core java volume 2 , 测试源代码均为原创, 旨在理解 java国际化--日期和时间+排序 的基础知识 : [1]日期和时间 1)当格 ...

  3. Java的日期与时间之如何计算业务代码的运行时间呢?

    转自: Java的日期与时间之如何计算业务代码的运行时间呢? 下文笔者讲述计算运行时间的方法分享,如下所示 实现思路:在业务开始时间和结束时间都加入获取时间的方法然后相减即可得到运行时间 例: lon ...

  4. Java 8 - 日期和时间实用技巧

    Java 8 – 日期和时间实用技巧 当你开始使用Java操作日期和时间的时候,会有一些棘手.你也许会通过System.currentTimeMillis() 来返回1970年1月1日到今天的毫秒数. ...

  5. Java 8 日期、时间、时间矫正器操作

    Java 8 日期.时间操作 真放肆不在饮酒放荡,假矜持偏要慷慨激昂.万事留一线,江湖好相见–老郭经典语录 本篇描述LocalDate.LocalTime.LocalDateTime.Temporal ...

  6. Java的日期与时间java.time.Duration的简介说明

    转自: Java的日期与时间java.time.Duration的简介说明 下文笔者讲述Duration类的简介说明,如下所示 Duration类简介 Duration对象:表示两个Instant间的 ...

  7. LocalDateTime - Java处理日期和时间

    java.time包提供了新的日期和时间的API,新的API主要包括:1. LocalDate/LocalTime/LocalDateTime2. ZoneDateTime/ZoneId3. Inst ...

  8. Date - Java处理日期和时间

    在计算机中如何表示日期和时间呢,我们可以想到有几种表示方式,一种是2016-11-20 8::15:01 GMT+08:00,或者我们用其他的时区,比如GMT+00:00标准时区,或者 America ...

  9. Java 8日期和时间

    如今,一些应用程序仍在使用java.util.Date和java.util.Calendar API,包括使我们的生活更轻松地使用这些类型的库,例如JodaTime. 但是,Java 8引入了新的AP ...

  10. 深入了解Java 8日期和时间API

    在这篇文章中,我们将更深入地了解通过Java 8获得的新的Date / Time API( JSR 310 ). 请注意,本文主要由显示新API功能的代码示例驱动. 我认为这些示例是不言自明的,因此我 ...

最新文章

  1. 清华团队将Transformer用到3D点云分割上后,效果好极了
  2. 《预训练周刊》第17期:深度迁移学习与数据增强改善2型糖尿病预测、钢琴补谱应用...
  3. VTK:libvtkGUISupportQt-6.3.so.1: cannot open shared object
  4. 富文本编辑器、日期选择器、软件天堂、防止XSS攻击、字体icon、转pdf
  5. 665C. Simple Strings
  6. 【转】彻底理解cookie,session,token
  7. 开源目标检测算法用于交通标志检测全方位评估
  8. C#文件目录IO常见操作汇总
  9. 12 File and Device I/O using System Calls
  10. 获得中文每个字的拼音首字母
  11. 使用sever2008做DHCP中继代理
  12. 最小二乘法求解线性回归模型及求解
  13. 白开水最耐喝,最解内心的渴
  14. Teradata天睿公司任命王波为大中华区总裁
  15. 这是一篇假的回顾过去展望未来计划书
  16. 天津理工大学计算机最牛导师,孟祥太_天津理工大学研究生导师信息
  17. 十三款流行的无线网络黑客工具介绍
  18. 基于多项式拟合的结构光系统标定
  19. 64位服务器系统gho,win7gho
  20. Linux系统使用EPSON的L3255型号打印机遇到的问题解决方法

热门文章

  1. 黑森林理论,猜疑链思考
  2. VS 用户自定义控件未出现在工具箱的解决方案
  3. 自动驾驶芯片之——FPGA和ASIC介绍
  4. 中国十大计算机学院排名2015,中国计算机学院排名
  5. 各地2022年上半年软考考试疫情防控要求汇总-2022-05更新
  6. IMDB数据看影响电影票房的因素分析
  7. Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon runn
  8. shopnc mysql_(转) shopnc数据库操作
  9. VS2013中关于gets函数使用问题的解决方案(搬运“尼古拉斯罗本”的部分文章,)
  10. Java 面试之单子模式