String specificDate=2013+"-"+06+"-"+20;
String day="Monday";
How to find the next date where Monday comes that is after that specificDate
?
String specificDate=2013+"-"+06+"-"+20;
String day="Monday";
How to find the next date where Monday comes that is after that specificDate
?
You either want to look at Java's Calendar or JodaTime, given you're looking at rules over dates, I'd recommend Joda.
Calendar now = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(formatString);
now.setTime(sdf.parse(dateString));
int weekday = now.get(Calendar.DAY_OF_WEEK);
if (weekday != Calendar.MONDAY)
{
int days = (Calendar.SATURDAY - weekday + 2) % 7;
now.add(Calendar.DAY_OF_YEAR, days);
}
Date monday = now.getTime();
You should really use a higher level Date library to do that for you. Unfortunately, java's built in Date and Calendar class are far less than ideal. You can take a look at this library, which has come the de facto standard for date manipulation among Java developers, until the new JDK design is finalized.
You should use the Calendar class for that.
Calendar c1 = Calendar.getInstance();
c1.set(2013, Calendar.JUNE, 20);
int weekday = now.get(Calendar.DAY_OF_WEEK);
if (weekday != Calendar.MONDAY) {
// calculate how much to add
// the 2 is the difference between Saturday and Monday
int days = (Calendar.SATURDAY - weekday + 2) % 7;
now.add(Calendar.DAY_OF_YEAR, days);
}
try this
Calendar c = new GregorianCalendar(2013, 5, 20);
int diff = Calendar.MONDAY - c.get(Calendar.DAY_OF_WEEK);
if (diff < 0) {
diff = 7 + diff;
}
c.add(Calendar.DATE, diff);
Date monday = c.getTime();
The easiest way to do this with the standard API is setting the day of week to Monday and then advancing one week:
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); // Sets c to this week's Monday
c.add(Calendar.DATE, 7); // Advances c to next week's Monday
Note that if the first day of the week in your culture is Sunday and the date your start with is a Sunday, the set
method moves the date to the following Monday-not the preceding one-and you end up calculating second Monday after the given date. If the first day of the week is Monday everything works as expected.
For Java 8, you could use something like...
LocalDate date = LocalDate.of(2013, Month.JUNE, 20);
LocalDate nextWed2 = date.with(TemporalAdjusters.nextOrSame(DayOfWeek.MONDAY));
or...
LocalDate date = LocalDate.of(2013, Month.JUNE, 20);
LocalDate nextWed2 = date.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
if the select date was MONDAY
, but you wanted the next MONDAY
As demonstrated here in much more detail
Or if you prefer to use JodaTime...
LocalDate date = new LocalDate(2013, DateTimeConstants.JUNE, 20);
LocalDate nextMonday = new LocalDate(date);
if (date.getDayOfWeek() >= DateTimeConstants.FRIDAY) {
nextMonday = date.plusWeeks(1);
}
nextMonday = nextMonday.withDayOfWeek(DateTimeConstants.FRIDAY);
Which is based on this answer