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

前端 未结 6 1078
醉酒成梦
醉酒成梦 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条回答
  •  -上瘾入骨i
    2021-02-15 02:38

    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.

提交回复
热议问题