Java8时间api之LocalDate/LocalDateTime的用法详解

  

Java8时间API之LocalDate/LocalDateTime的用法详解

Java8提供了全新的时间日期API,提供了更好的灵活性和易用性。其中,LocalDate和LocalDateTime是比较常用的类,下面详细讲解它们的用法。

LocalDate

LocalDate是纯日期类,不包含时间。它的使用方式如下:

// 获取当前日期
LocalDate today = LocalDate.now();
System.out.println("今天的日期是:" + today);

// 通过字符串解析日期
LocalDate date = LocalDate.parse("2019-10-01");
System.out.println("解析出的日期是:" + date);

// 创建指定日期的LocalDate实例
LocalDate specifiedDate = LocalDate.of(2019, 10, 1);
System.out.println("指定的日期是:" + specifiedDate);

// 计算日期之间的差距
Period period = Period.between(date, today);
System.out.println("距离指定日期" + date + "已经过了" + period.getMonths() + "个月零" + period.getDays() + "天");

在上述示例代码中,LocalDate.now()方法用于获取当前日期,LocalDate.parse(String date)方法用于通过字符串解析日期,LocalDate.of(int year, int month, int dayOfMonth)方法用于创建指定日期的LocalDate实例,Period.between(Temporal startInclusive, Temporal endExclusive)方法用于计算日期之间的差距。

LocalDateTime

LocalDateTime是日期和时间类,它是LocalDate和LocalTime的合体。它的使用方式如下:

// 获取当前日期和时间
LocalDateTime now = LocalDateTime.now();
System.out.println("当前的日期和时间是:" + now);

// 通过字符串解析日期和时间
LocalDateTime dateTime = LocalDateTime.parse("2019-10-01T12:34:56");
System.out.println("解析出的日期和时间是:" + dateTime);

// 创建指定日期和时间的LocalDateTime实例
LocalDateTime specifiedDateTime = LocalDateTime.of(2019, 10, 1, 12, 34, 56);
System.out.println("指定的日期和时间是:" + specifiedDateTime);

// 计算时间之间的差距
Duration duration = Duration.between(dateTime, now);
System.out.println("距离指定日期和时间" + dateTime + "已经过了" + duration.toDays() + "天" + duration.toHours() % 24 + "小时");

在上述示例代码中,LocalDateTime.now()方法用于获取当前日期和时间,LocalDateTime.parse(String dateTime)方法用于通过字符串解析日期和时间,LocalDateTime.of(int year, int month, int dayOfMonth, int hour, int minute, int second)方法用于创建指定日期和时间的LocalDateTime实例,Duration.between(Temporal startInclusive, Temporal endExclusive)方法用于计算时间之间的差距。

示例说明

示例一

需求:计算2020年10月1日和2021年3月3日之间相差的天数。

LocalDate date1 = LocalDate.of(2020, 10, 1);
LocalDate date2 = LocalDate.of(2021, 3, 3);
Period period = Period.between(date1, date2);
System.out.println("相差的天数为:" + period.getDays());

输出结果:相差的天数为:0

示例二

需求:计算2020年10月1日下午3点到2020年10月2日上午8点相差的小时数。

LocalDateTime dateTime1 = LocalDateTime.of(2020, 10, 1, 15, 0, 0);
LocalDateTime dateTime2 = LocalDateTime.of(2020, 10, 2, 8, 0, 0);
Duration duration = Duration.between(dateTime1, dateTime2);
System.out.println("相差的小时数为:" + duration.toHours());

输出结果:相差的小时数为:17

以上就是Java8时间API之LocalDate/LocalDateTime的用法详解,希望能够对大家有所帮助。

相关文章