java8中LocalDateTime的使用

本文通过实例展示了Java8中LocalDateTime的用法,包括与String的相互转换、设置偏移、获取日期值、比较日期顺序及计算时间间隔。

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

直接上例子

@Test
    public void test1(){
        // 获取当前时间的两种方法
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.now(), ZoneId.systemDefault());
        System.out.println(now);
        System.out.println(localDateTime);

        // 指定具体日期
        LocalDateTime time1 = LocalDateTime.of(2019, 1, 22, 14, 3, 20);
        System.out.println(time1);
    }

结果如下, 注意 LocalDateTime输出形式

2019-12-13T09:48:48.410
2019-12-13T09:48:48.410
2019-01-22T14:03:20

String和 LocalDateTime 互相转换

@Test
    public void test2(){
        // LocalDateTime 转String
        LocalDateTime time1 = LocalDateTime.of(2019, 1, 22, 14, 3, 20);
        String timeStr1 = time1.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        System.out.println(timeStr1);

        // String 转 LocalDateTime, 注意把 yyyy-MM-dd HH:mm:ss 中空格地方换为字符'T'
        timeStr1 = timeStr1.replace(' ', 'T');
        System.out.println("timeStr1:" + timeStr1);
        LocalDateTime time2 = LocalDateTime.parse(timeStr1);
        System.out.println(time2);
    }

在这里插入图片描述

LocalDateTime 的偏移

@Test
    public void test3(){
    // 年月日时分秒, 都可作为偏移单位; 可以偏移负数
        LocalDateTime time1 = LocalDateTime.of(2019, 1, 22, 14, 3, 20);
        System.out.println(time1.plusDays(-20));
        System.out.println(time1.plusHours(10));
        System.out.println(time1.plusMinutes(-10));
        System.out.println(time1.plusMonths(1));
        System.out.println(time1.plusSeconds(11));
        System.out.println(time1.plusYears(2));
    }

在这里插入图片描述

LocalDateTime 取日期相关值 以及日期先后的比较

@Test
    public void test4(){
        LocalDateTime time1 = LocalDateTime.of(2019, 1, 22, 14, 3, 20);
        // 从LocalDateTime 直接取值
        System.out.println(time1.getDayOfMonth());
        System.out.println(time1.getHour());
        System.out.println(time1.getMonthValue());

        // LocalDateTime的比较
        System.out.println(LocalDateTime.now().isAfter(time1));
    }

在这里插入图片描述

比较LocalDateTime 之间的时间间隔

 @Test
    public void test5(){
        // 使用 Duration 比较时间间隔(向下取整)
        LocalDateTime time1 = LocalDateTime.of(2019, 1, 22, 14, 3, 20);
        Duration between = Duration.between(time1, LocalDateTime.now());
        System.out.println(between);

        System.out.println(between.toDays());
        System.out.println(between.toHours());
        System.out.println(between.getSeconds());
        System.out.println(between.toMillis());
    }

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值