tags:

views:

112

answers:

3

For instance in Sept I would need:

1,8,15,22 and 29

Thanks

+7  A: 

Look up the Doomsday Rule - you should be able to apply that algorithm to your problem.

Smashery
Excellent...many years ago I came across this algorithm but did not know what it was called so I could not find it back.
Vincent Ramdhanie
If this calculation needs to be done a lot, then the Doomsday algorithm will probably be a lot faster.
jnylen
+3  A: 

The simplest (naive) solution I can see is:

Get a Calendar (Calendar.getInstance())

Set the year, month, date etc (zero out other fields).

Then iterate adding one to the date (stop if you're not in the correct month - calendar.get(Calendar.MONTH))

while iterating, if calendar.get(Calendar.DAY_OF_WEEK) == Calendar.TUESDAY then increment the Tuesday counter.

daveb
Well I wouldn't increment the counter but add it to a list or something. I've coded your algorithm and runs fine. Thanks
OscarRyz
You really needed Stack Overflow to come up with *that* solution? You’re kidding me, right?
Bombe
A: 

As per daveb answer I've got:

import java.util.Calendar;
import static  java.util.Calendar.*;

public class DiasDelMes {

    public static void main( String [] args ) {

        Calendar calendar = getInstance();

        calendar.set( DAY_OF_MONTH, 1  );

        int month = calendar.get( MONTH );

        while( calendar.get( MONTH ) == month ) { 

            if( calendar.get( DAY_OF_WEEK ) == TUESDAY ) {
                 System.out.println( calendar.get( DAY_OF_MONTH ) ) ;
            }

            calendar.add( DAY_OF_MONTH , 1 ); 
       }
    }
}
OscarRyz