How to detect if a date is within this or next week in java?

前端 未结 6 1244
醉酒成梦
醉酒成梦 2021-02-15 01:59

If I have a date of an event, such as 2011-01-03, how to detect if it is within this or next week in java ? Any sample code ?

Edit :

I thought it was a simple qu

6条回答
  •  不要未来只要你来
    2021-02-15 02:58

    Although old question - is still relevant. The most upvoted answer here is correct wrt to Joda-time and wrt to JDK8 as well with some syntax changes. Here's one that might help those who are looking around in JDK8 world.

     public static boolean isLocalDateInTheSameWeek(LocalDate date1, LocalDate date2) {
        LocalDate sundayBeforeDate1 = date1.with(TemporalAdjusters.previousOrSame(DayOfWeek.SUNDAY));
        LocalDate saturdayAfterDate1 = date1.with(TemporalAdjusters.nextOrSame(DayOfWeek.SATURDAY));
        return  ((date2.isEqual(sundayBeforeDate1) || date2.isAfter(sundayBeforeDate1)) 
                && (date2.isEqual(saturdayAfterDate1) || date2.isBefore(saturdayAfterDate1)));
    }
    

提交回复
热议问题