字符串和LocalDateTime互转、计算时间差

该博客演示了如何在Java中将字符串转换为LocalDateTime对象,并进行时间比较。它还展示了获取时间字段的方法,并提供了计算时间差的API示例,如Duration.between()用于计算两个时间点之间的差距。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    public static void main(String[] args) {
        // 字符串转LocalDateTime
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime endTime = LocalDateTime.parse("2021-11-12 17:21:35",df);
        // 当前时间
        LocalDateTime time = LocalDateTime.now();
        System.out.println("当前时间是否大于指定时间:"+ time.isAfter(endTime));
        System.out.println("年:"+endTime.getYear() +" 月:" + endTime.getMonthValue());
        System.out.println("日:"+endTime.getDayOfMonth() +" 时:" + endTime.getHour());
        System.out.println("分:"+endTime.getMinute() +" 秒:" + endTime.getSecond());
        // LocalDateTime转字符串
        String localTime = df.format(time);
        System.out.println("字符串时间:"+ localTime);
    }

结果:

当前时间是否大于指定时间:true
年:2021 月:11
日:12 时:17
分:21 秒:35
字符串时间:2021-11-15 11:05:18

计算时间差:

LocalDateTime.now() 获得当前时间

java.time.Duration duration = java.time.Duration.between(LocalDateTime   startTime,  LocalDateTime  endTime );


例如:     duration.toMinutes()    //两个时间差的分钟数

toNanos()//纳秒

toMillis()//毫秒

toMinutes()//分钟

toHours()//小时

toDays()//天数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值