Get the last day of the next three weeks of Java

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

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

I wrote a function like

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

DateUtils is used from this library:

org.apache.commons.lang.time.DateUtils;

But this function will return on Wednesday, May 7, which means that it will return exactly on the day of the current date.

No need to rewrite my function. Any other ways to solve my problem would be very helpful. Thank you

+4
source share
5 answers

Use the code below, hoping it helps

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

Just try:

Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
c.add(Calendar.WEEK_OF_YEAR, 2);

DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
System.out.println(df.format(c.getTime()));

Output:

2014/05/04
+1
source

- :

Calendar calendar = Calendar.getInstance().getFirstDayOfWeek();
calendar.add(Calendar.WEEK_OF_YEAR, 4);
calendar.add(Calendar.DAY_OF_MONTH, -1);
+1

Java

, ,

    Date d = new Date();
    GregorianCalendar cal1  =  new GregorianCalendar();
    cal1.setTime(d);
    System.out.println(cal1.getTime());
    int day = cal1.get(Calendar.DAY_OF_WEEK );
    cal1.add(Calendar.DAY_OF_YEAR,-(day-1));/*go to start of the week*/
    cal1.add(Calendar.WEEK_OF_YEAR,3); // add 3 weeks 
    day = cal1.get(Calendar.DAY_OF_MONTH );// get the end Day of the 3rd week
    System.out.println("end of the 3rd week  ="+day);
+1

.

java.time

java.time Java 8 . , java.util.Date .Calendar. . Oracle. java.time Java 6 7 ThreeTen-Backport Android ThreeTenABP.

LocalDate . TemporalAdjuster LocalDate . TemporalAdjusters ( ) , , , nextOrSame( WeekOfDay ). WeekOfDay - , , -.

LocalDate start = LocalDate.of ( 2014 , Month.APRIL , 16 );
LocalDate nextOrSameSunday = start.with ( TemporalAdjusters.nextOrSame ( DayOfWeek.SUNDAY ) );
LocalDate twoWeeksAfterNextOrSameSunday = nextOrSameSunday.plusWeeks ( 2 );

.

System.out.println ( "start: " + start + " | nextOrSameSunday: " + nextOrSameSunday + " | twoWeeksAfterNextOrSameSunday: " + twoWeeksAfterNextOrSameSunday );

: 2014-04-16 | nextOrSameSunday: 2014-04-20 | twoWeeksAfterNextOrSameSunday: 2014-05-04

+1

Source: https://habr.com/ru/post/1536731/


All Articles