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
Most answers here do not satisfy me. They either use the outdated Calendar
-API (excusable in old answers given in times before Java 8, and it is hence not fair to criticize such answers), or they are even partially wrong or unnecessarily complex. For example, the most upvoted answer by Jon Skeet suggests to determine the first day of week by the Joda-expression new LocalDate().withDayOfWeek(DateTimeConstants.SUNDAY)
. But such code uses the ISO-definition of a week starting on Monday with the consequence that if the current date is not on Sunday the code would produce next Sunday and not previous Sunday as desired by the OP. Joda-Time is incapable of handling non-ISO weeks.
Another minor flaw of other answers is not to care about if the current AND NEXT week contains a given date - as requested by the OP. So here my improved suggestion in modern Java:
LocalDate today = LocalDate.now(); // involves the system time zone and clock of system
LocalDate startOfCurrentWeek =
today.with(TemporalAdjusters.previousOrSame(DayOfWeek.SUNDAY));
LocalDate endOfNextWeek =
startOfCurrentWeek.plusDays(13);
LocalDate event = LocalDate.of(2011, 1, 3); // input of example given by OP
boolean matchingResult =
!(event.isBefore(startOfCurrentWeek) || event.isAfter(endOfNextWeek));
Side note: The question has inspired me to add a small enhancement to the class DateInterval
in my library Time4J how to determine the current calendar week in a very generic way.