026——JDK8开始新增日期API

JDK8开始新增日期API

概述、LocalTime /LocalDate / LocalDateTime

概述

  • 从Java 8开始,java.time包提供了新的日期和时间API,主要涉及的类型有:

img

  1. 新增的API严格区分了时刻、本地日期、本地时间,并且,对日期和时间进行运算更加方便。
  2. 其次,新API的类型几乎全部是不变类型(和String的使用类似),可以放心使用不必担心被修改。

LocalDate、LocalTime、LocalDateTime

他们 分别表示日期,时间,日期时间对象,他们的类的实例是不可变的对象。
他们三者构建对象和API都是通用的

img

LocalDate、LocalTime、LocalDateTime获取信息的API.

img

转换相关的API

img

修改相关的API

img

Instant

Instant时间戳

JDK8获取时间戳特别简单,且功能更丰富。Instant类由一个静态的工厂方法now()可以返回当前时间戳

img

时间戳是包含日期和时间的,与java.util.Date很类似,事实上Instant就是类似JDK8 以前的Date。
Instant和Date这两个类可以进行转换。

DateTimeFormatter

在JDK8中,引入了一个全新的日期与时间格式器DateTimeFormatter。
正反都能调用format方法。

img

代码演示

package com.google.d4_jdk8_time;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author North
 * @date 2022/10/24 12:26
 */
public class DateTimeFormatDemo {
    public static void main(String[] args) {
        // 本地此刻 日期时间 对象
        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println(localDateTime);

        System.out.println("------------------");

        // 解析 / 格式化器
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss EE");

        // 正向格式化
        System.out.println(dateTimeFormatter.format(localDateTime));

        // 逆向格式化
        System.out.println(localDateTime.format(dateTimeFormatter));

        // 解析字符串时间
        DateTimeFormatter dateTimeFormatter_1 = DateTimeFormatter.ofPattern("yyyy-dd HH:mm:ss");

        // 解析当前字符串时间成为本地日期时间对象
        System.out.println(localDateTime.format(dateTimeFormatter_1));
    }
}

Duration/Period

Period

  1. 在Java8中,我们可以使用以下类来计算日期间隔差异:java.time.Period
  2. 主要是 Period 类方法 getYears(),getMonths() 和 getDays() 来计算,只能精确到年月日。
  3. 用于 LocalDate 之间的比较。

img

代码演示

package com.google.d4_jdk8_time;

import java.time.LocalDate;
import java.time.Period;

/**
 * @author North
 * @date 2022/10/24 12:33
 */
public class PeriodDemo {
    public static void main(String[] args) {
        // 当前本地 年月日
        LocalDate localDate = LocalDate.now();
        System.out.println(localDate);

        // 生日的 年月日
        LocalDate birthDate = LocalDate.of(2001 ,3 ,3);
        System.out.println(birthDate);

        Period period = Period.between(birthDate , localDate);
        System.out.println(period.getYears());
        System.out.println(period.getMonths());
        System.out.println(period.getDays());
    }
}

Duration

  1. 在Java8中,我们可以使用以下类来计算时间间隔差异:java.time.Duration
  2. 提供了使用基于时间的值测量时间量的方法。
  3. 用于 LocalDateTime 之间的比较。也可用于 Instant 之间的比较。

img

总结

img

ChronoUnit

java.time.temporal.ChronoUnit

ChronoUnit类可用于在单个时间单位内测量一段时间,这个工具类是最全的了,可以用于比较所有的时间单位

img

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值