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

前端 未结 5 2056
半阙折子戏
半阙折子戏 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:37

    It partly depends on what you mean by "this week" and "next week"... but with Joda Time it's certainly easy to find out whether it's in "today or the next 7 days" as it were:

    LocalDate event = getDateFromSomewhere();
    LocalDate today = new LocalDate();
    LocalDate weekToday = today.plusWeeks(1);
    LocalDate fortnightToday = weekToday.plusWeeks(1);
    
    if (today.compareTo(event) <= 0 && event.compareTo(weekToday) < 0)
    {
        // It's within the next 7 days
    }
    else if (weekToday.compareTo(event) <= 0 && event.compareTo(fornightToday) < 0)
    {
        // It's next week
    }
    

    EDIT: To get the Sunday to Saturday week, you'd probably want:

    LocalDate startOfWeek = new LocalDate().withDayOfWeek(DateTimeConstants.SUNDAY);
    

    then do the same code as the above, but relative to startOfWeek.

提交回复
热议问题