美文网首页
JAVA7,8两个日期对比是否跨过几个月份

JAVA7,8两个日期对比是否跨过几个月份

作者: IT男的假智慧 | 来源:发表于2023-10-15 16:49 被阅读0次

public static void main(String[] args) {

// 示例:假设有两个时间点 t1 和t2

        String t1 ="2023-01-01";

        String t2 ="2023-02-28";

        if (isMoreThanTwoMonths(t1, t2) >=2) {

System.out.println("=======超过两个月了哦==========");

        }else {

System.out.println("=======没有超过两个月==========");

        }

}

////java7写法

    public static int isMoreThanTwoMonths(String startDate, String endDate) {

SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd");

        try {

Calendar cal1 = Calendar.getInstance();

            cal1.setTime(sdf.parse(startDate));

            Calendar cal2 = Calendar.getInstance();

            cal2.setTime(sdf.parse(endDate));

            return (cal2.get(Calendar.YEAR) - cal1.get(Calendar.YEAR)) *12 + cal2.get(Calendar.MONTH) - cal1.get(Calendar.MONTH);

        }catch (ParseException e) {

e.printStackTrace();

        }

return 0;

    }

//java8写法

    public static boolean isMoreThanTwoMonths(String startDate, String endDate) {

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        try {

LocalDate date1 = LocalDate.parse(startDate, formatter);

            LocalDate date2 = LocalDate.parse(endDate, formatter);

            return date2.isAfter(date1.plusMonths(2));

        }catch (Exception e) {

return false;

        }

}

相关文章

网友评论

      本文标题:JAVA7,8两个日期对比是否跨过几个月份

      本文链接:https://www.haomeiwen.com/subject/tlitidtx.html