JDK8新时间类(二)

本文介绍了Java中的DateTimeFormatter类,用于时间的格式化和解析,以及如何使用LocalDateTime和Period/Duration类计算日期/时间间隔。通过实例展示了如何创建和操作这些类以处理日期和时间数据。
摘要由CSDN通过智能技术生成

DateTimeFormatter

格式化器,用于时间的格式化、解析

方法名说明
public static DateTimeFormatter ofPattern(时间格式)获取格式化器对象
public String format(时间对象)格式化时间

LocalDateTime提供的格式化、解析时间的方法

方法名说明
public String format(DateTimeFormatter formatter)格式化时间
public static LocalDateTime parse(CharSequence text, DateTimeFormatter formatter)解析时间

案例演示

public class DateTimeFormatterTest {
    public static void main(String[] args) {
        //创建一个日期时间格式化器对象
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日  HH:mm:ss");

        //对时间进行格式化
        LocalDateTime now = LocalDateTime.now();
        System.out.println(now);
        System.out.println(formatter.format(now));  //正向格式化

        //格式化时间方案2
        System.out.println("-----------");
        System.out.println(now.format(formatter));  //反向格式化

        //解析时间:解析时间一般使用LocalDateTime提供的解析方法来解析
        System.out.println("-----------");
        String dateStr = "2020年05月20日  05:20:20";
        LocalDateTime ldt = LocalDateTime.parse(dateStr, formatter);
        System.out.println(ldt);
    }
}

Period(一段时期)

可以用于计算两个LocalDate对象相差的年数、月数、天数

Period常见方法

方法名说明
public static Period between(LocalDate start, LocalDate end)传入2个日期对象,得到Period对象
public int getYears()计算隔几年,并返回
public int getMonths()计算隔几个月,并返回
public int getDays()计算隔多少天,并返回

案例演示

public class PeriodTest {
    public static void main(String[] args) {
        LocalDate ld1 = LocalDate.of(2020, 5, 20);
        LocalDate ld2 = LocalDate.now();
        //创建Period对象,封装两个日期对象
        Period period = Period.between(ld1, ld2);

        //间隔多少年
        System.out.println(period.getYears());  //只计算年份间隔
        //间隔多少月
        System.out.println(period.getMonths()); //只计算月份间隔,不考虑年份
        //间隔多少天
        System.out.println(period.getDays());   //只计算号数(DayOfMonth)数间隔,不考虑年和月
    }
}

Duration(持续时间)

可以用于计算两个时间对象相差的天数、小时数、分数、秒数、纳秒数;支持LocalTime、LocalDate、LocalDateTime、Instant等时间

方法名说明
public static Duration between(开始时间对象1, 截止时间对象2)传入2个时间对象,得到Duration对象
public long toDays()计算隔多少天,并返回
public long toHours()计算隔多少小时,并返回
public long toMinutes()计算隔多少分,并返回
public long toSeconds()计算隔多少秒,并返回
public long toMillis()计算隔多少毫秒,并返回
public long toNanos()计算隔多少纳秒,并返回
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

离歌慢饮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值