搜索
您的当前位置:首页正文

LocalDateTime 比较大小,计算两个LocalDateTime的时间差时分秒

来源:好走旅游网

LocalDateTime 比较大小

最近开发快递物流轨迹对接 获取 快递轨迹的时候 需要 判断哪些轨迹信息是 已经保存过得 必须进行 时间比较
实体用的都是 年月时间 格式 以下是LocalDateTime 比较方法

public static void main(String[] args) {
        //获取当前时间
        LocalDateTime nowTime= LocalDateTime.now();
        //自定义时间
        LocalDateTime endTime = LocalDateTime.of(2021, 10, 23, 14, 10, 10);
        //比较  如今的时间 在 设定的时间 之后  返回的类型是Boolean类型
        System.out.println(nowTime.isAfter(endTime));
        //比较   如今的时间 在 设定的时间 之前  返回的类型是Boolean类型
        System.out.println(nowTime.isBefore(endTime));
        //比较   如今的时间 和 设定的时候  相等  返回类型是Boolean类型
        System.out.println(nowTime.equals(endTime));
    }

例子 :
如果是之后就进行存储

   //第一种
        String time1 = "2019-06-26 19:00:00";
        DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime localDateTime = LocalDateTime.parse(time1, dtf2);
        System.out.println(localDateTime.isBefore(LocalDateTime.now()));//你的时间在当前时间之前是true
        System.out.println(localDateTime.isAfter(LocalDateTime.now()));//在当前时间之后是false
     //第二种
     LocalDateTime now = LocalDateTime.now();
     Duration duration = Duration.between(now,now);
        System.out.println(duration);
        long days = duration.toDays(); //相差的天数
        long hours = duration.toHours();//相差的小时数
        long minutes = duration.toMinutes();//相差的分钟数
        long millis = duration.toMillis();//相差毫秒数
        long nanos = duration.toNanos();//相差的纳秒数
        System.out.println(millis);
     //第三种
        long mills = now.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        System.out.println(mills >= System.currentTimeMillis());

计算时间差时分秒

方法1

        LocalDateTime fromDate = LocalDateTime.now();
        LocalDateTime toDate = LocalDateTime.now().plusHours(40);

        long minutes = ChronoUnit.MINUTES.between(fromDate, toDate);
        long hours = ChronoUnit.HOURS.between(fromDate, toDate);

        System.out.println(minutes);
        System.out.println(hours);

方法2

         LocalDateTime fromDate = LocalDateTime.now();
         LocalDateTime toDate = LocalDateTime.now().plusHours(40);

         Duration duration = Duration.between(fromDate, toDate);

        long minuts = duration.toMinutes();
        long hours = duration.toHours();

例子:

因篇幅问题不能全部显示,请点此查看更多更全内容

Top