Giri Giri - 9 months ago 39
Java Question

Get the Week day List in a Month For specified week day

I need to prepare a list of week day dates

Note :- Week day are not satudrday or sunday, (I can pass the Week day as parameter)

I have written following code but not working,
Can you please correct the code

public static void main (String[] args) {

List weekoffDates = new ArrayList<Timestamp>();
Timestamp date = "2013-12-01 00:00:00.0"; //This is timestamp object not string
Timestamp endDate = "2013-12-31 00:00:00.0"; //This is timestamp object not string
int dayOfWeek = 3 //TuesDay

for ( int i =1 ; i<=5; i++ ) {
if( ! date.after(endDate) ) {
Calendar calendar = Calendar.getInstance();
calendar.set( Calendar.DAY_OF_WEEK, dayOfWeek ); //This is my parameter
//calendar.set( Calendar.WEEK_OF_MONTH, i );
date = new Timestamp( calendar.getTimeInMillis() );
dayOfWeek = dayOfWeek +7;


date :- 2013:December:1 (I have sent as Timestamp object)

EndDate :- 2013:December:31 (I have sent as Timestamp object)

dayOfWeek :- This is Day Of Week ( I have sent this parameter as tuesday 3 ) //It will change dynamically

Expected Result :-

All tuesday in the month of decemer as ArrayListlist

Problem :- calendar.set( Calendar.DAY_OF_WEEK, dayOfWeek ); setting is wrong

Answer Source

You would have to iterate over the days between start and end days. Within the iterating loop, you can check for the day your need to store and then store it in your list.

Below is a crude working example which you can modify according to your best practices or different data types which you might want to use:

public static void main(String[] args) {
        List<String> workDays = new ArrayList<String>();
        int dayOfWeek  = 3; //TuesDay

        Calendar startDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();

        startDate.set(2013, 11, 1);
        endDate.set(2013, 11, 31);

        while (startDate.getTimeInMillis() <= endDate.getTimeInMillis()) {
            if (startDate.get(Calendar.DAY_OF_WEEK) == dayOfWeek) {
            startDate.add(Calendar.DAY_OF_MONTH, 1);


Note the hardcoded start and end dates have month parameter as 11 for Deember, since January = 0 under java.util.Calendar

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download