Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

date

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 question, it turned out more complex than I thought, what I meat this week is : from this past Sun to this Sat, next week is from next Sun to the Sat after that.

like image 749
Frank Avatar asked Dec 26 '10 21:12

Frank


1 Answers

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.

like image 102
Jon Skeet Avatar answered Sep 23 '22 23:09

Jon Skeet