java8操作时间

LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println("当前时间:" + localDateTime);//2020-12-08T11:19:04.305

        LocalDateTime localDateTime1 = LocalDateTime.of(2020, 06, 02, 12, 22, 23);
        System.out.println("指定时间:" + localDateTime1);//2020-06-02T12:22:23

        //手动指定时间 当天0点
        LocalDateTime localDateTime11 = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0);
        System.out.println("手动指定日期时间当天0点:" + localDateTime11);//2020-12-08T00:00:00.306

        LocalDateTime localDateTime2 = LocalDateTime.now().plusMonths(2);
        System.out.println("当前时间添加2月:" + localDateTime2);//2021-02-08T11:19:04.306

        LocalDateTime localDateTime3 = LocalDateTime.now().minusDays(2);
        System.out.println("当前时间减少2天:" + localDateTime3);//2020-12-06T11:19:04.306

        // 获取秒数
        Long second = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
        System.out.println("获取秒数" + second);//1607397544

        // 获取毫秒数方法1
        Long milliSecond = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
        System.out.println("获取毫秒数1:" + milliSecond);//1607397544306

        //获取毫秒数方法2
        long milliSecond2 = Instant.now().toEpochMilli();
        System.out.println("获取毫秒数2:" + milliSecond2);//1607397544307

        LocalDateTime localDateTime21 = LocalDateTime.now().withDayOfMonth(10);
        System.out.println("手动指定日期时间:" + localDateTime21);//2020-12-10T11:19:04.307

        LocalDateTime with = LocalDateTime.now().with(TemporalAdjusters.firstDayOfMonth());
        System.out.println("使用TemporalAdjuster获取当月第一天:" + with);//2020-12-01T11:19:04.307

        System.out.println("获取下一年的第一天:" + localDateTime.with(TemporalAdjusters.firstDayOfNextYear()));//2021-01-01T11:19:04.305
        System.out.println("获取年中最后一天" + localDateTime.with(TemporalAdjusters.lastDayOfYear()));//2020-12-31T11:19:04.305
        System.out.println("获取月中最后一天" + localDateTime.with(TemporalAdjusters.lastDayOfMonth()));//2020-12-31T11:19:04.305
        System.out.println("获取下个星期一" + localDateTime.with(TemporalAdjusters.next(DayOfWeek.MONDAY)));//2020-12-14T11:19:04.305

        // 也可自定义格式
        DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 两种写法效果一样
        System.out.println("自定义格式化日期一:"+formatter1.format(LocalDateTime.now()));//2020-12-08 11:19:04
        System.out.println("自定义格式化日期二:"+LocalDateTime.now().format(formatter1));//2020-12-08 11:19:04

        // 字符串转换时间
        LocalDateTime parse = LocalDateTime.parse("2020-12-08 11:18:00", formatter1);
        System.out.println("字符串转日期:"+parse);//2020-12-08T11:18

 

上一篇:[转帖]备忘:CentOS-7 使用systemctl 管理的服务,文件打开数上限1024要改


下一篇:java中的LocalDate 和LocalDateTime 基础用法