JDK8 时间工具类

JDK8 Period

Period类计算的是年、月、日的间隔
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;

public class JDK8_LocalDate {
    public static void main(String[] args) {

        // 定义两个LocalDateTime对象
        LocalDateTime ldt1 = LocalDateTime.of(2023,2,11,3,16);
        LocalDateTime ldt2 = LocalDateTime.of(2024,2,11,3,16);

        // 将对象转换为LocalDate对象
        LocalDate date = ldt1.toLocalDate();
        LocalDate date1 = ldt2.toLocalDate();

        // 使用Period的between方法,计算两个对象相隔时间,并且返回时间
        Period between = Period.between(date,date1);
        
        // 打印对象
        System.out.println(between);

        // 通过对象.get方法获取需要的值
        int years = between.getYears();

        // 打印结果
        System.out.println(years);

    }
}

JDK8 Duration

Duration这个类计算的(秒、纳秒)的间隔
import java.time.*;

public class JDK8_LocalDate {
    public static void main(String[] args) {

        // 定义两个LocalDateTime对象
        LocalDateTime ldt1 = LocalDateTime.of(2023,2,11,3,16);
        LocalDateTime ldt2 = LocalDateTime.of(2024,2,11,3,16);

        // 将对象转换为LocalTime对象
        LocalTime localTime = ldt1.toLocalTime();
        LocalTime localTime1 = ldt2.toLocalTime();

        // 使用Duration可以计算两个时间之间的间隔
        Duration duration = Duration.between(localTime,localTime1);

        // 打印对象
        System.out.println(duration);

        // 使用对象获取需要的信息
        long seconds = duration.getSeconds();
        
        // 打印结果
        System.out.println(seconds);

    }
}

JDK8 ChronoUnit

ChronoUnit这个类包含了所有的时间单位

方法:ChronoUnit.XXX.between(时间1,时间2)

import java.time.*;
import java.time.temporal.ChronoUnit;

public class JDK8_LocalDate {
    public static void main(String[] args) {

        // 定义两个LocalDateTime对象
        LocalDateTime ldt1 = LocalDateTime.of(2023,2,11,3,16);
        LocalDateTime ldt2 = LocalDateTime.of(2024,2,11,3,16);

        // 计算两个时间相差的年份
        long between = ChronoUnit.YEARS.between(ldt1, ldt2);

        // 打印结果
        System.out.println(between);
        
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值