xtiger xtiger - 1 year ago 55
Java Question

Get the last day of next three weeks Java

I want to get the last day of next three weeks.

For example,if today is Wednesday,16 April ,I will get the result Sunday,4 May.

I have written a function like this

public static Date nexThreeWeekEnd() {
Date now = new Date();
Date nextWeeks = DateUtils.truncate(DateUtils.addWeeks(now, 3), Calendar.DATE);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DAY_OF_WEEK));
return calendar.getTime();

DateUtils is used from this library:


But this function will return Wednesday, 7 May, that's mean it will return exactly the day of current date.

It's not necessary to rewrite my function. Any other ways to solve my problem will be very appriciated.

Answer Source

Use below code hope it helps

   Calendar cal  = Calendar.getInstance();
   int currentDay = cal.get(Calendar.DAY_OF_WEEK);
   int leftDays= Calendar.SUNDAY - currentDay;
   cal.add(Calendar.DATE, leftDays)