0

How do i get a date by giving the week of the month and day of the week.

Example: If i need the third tuesday of November 2018.

Week of month : 3, Day of Week : 3

Expected date is : Nov 20 2018

But the value we get is : Nov 13 2018. Since the start day of the month (thursday) is less than than the expected day(tuesday).

   Calendar calendar = Calendar.getInstance();  
   calendar.set(Calendar.YEAR,2018 );  
   calendar.set(Calendar.MONTH, 10);  
   calendar.set(Calendar.WEEK_OF_MONTH, 3);  
   calendar.set(Calendar.DAY_OF_WEEK, 3);  
   System.out.println("Time " + calendar.getTime());

How do i get the correct date??

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Aju
  • 796
  • 3
  • 10
  • 29
  • If you just input the week of month and the day of week, then how do you determine which month it is? – deHaar Nov 21 '18 at 10:58
  • WEEK_OF_MONTH should be 4. Since 20th falls on 4th week of Nov. Works fine with this value. Tested. – bitsobits Nov 21 '18 at 11:03
  • The `Calendar` class has design problems and is long outdated. Use `java.time`, the modern Java date and time API. Depending on your definition of week numbers in a month the `WeekFields` class may be useful. – Ole V.V. Nov 21 '18 at 12:32

3 Answers3

3

If you are using Java 8, you can do this,

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;

public class Main {
    public static void main(String[] args) {
        LocalDate input = LocalDate.now();
        int ordinal = 3;
        DayOfWeek weekday = DayOfWeek.THURSDAY;
        TemporalAdjuster ta = TemporalAdjusters.dayOfWeekInMonth(ordinal, weekday) ;
        LocalDate adjusted = input.with( ta );
        System.out.println(adjusted.toString());
    }

}

I have taken it from here, and there are more ways to do that in the given link.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Sandeepa
  • 3,457
  • 5
  • 25
  • 41
2

You can use the following code :

LocalDate.now().with(TemporalAdjusters.dayOfWeekInMonth(3, DayOfWeek.TUESDAY));

This will output :

2018-11-20

More info can be found in the java docs here

Nicholas K
  • 15,148
  • 7
  • 31
  • 57
2

If you want to use Calendar then:

int year = 2018;
int month = 10;  // zero based November

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
calendar.set(Calendar.DAY_OF_WEEK_IN_MONTH, 3);
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.YEAR, year);
System.out.println(calendar.getTime());
forpas
  • 160,666
  • 10
  • 38
  • 76