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

前端 未结 5 2061
半阙折子戏
半阙折子戏 2021-02-15 02:05

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

5条回答
  •  孤独总比滥情好
    2021-02-15 02:44

    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)));
    }
    

提交回复
热议问题