본문 바로가기

IT칼럼/JAVA

지정된 달에서 특정요일(수, 금 ,토)에 해당하는 날짜 받아오기


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;

public class TestMain {
public static void main(String args[]) throws ParseException{
// create a Calendar for the 1st of the required month
//int year = 2019;
//int month = Calendar.APRIL;
String date = "04/17/2019";
String pattern = "MM/dd/yyyy";
        Date date1=new SimpleDateFormat(pattern).parse(date);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date1);
        
        //System.out.println(date1);
        int year = Calendar.getInstance().get(Calendar.YEAR);
        int month = Calendar.getInstance().get(Calendar.MONTH); // +1?
            
        Calendar cal = new GregorianCalendar(year, month, 1);
        do {
            // get the day of the week for the current day
            int day = cal.get(Calendar.DAY_OF_WEEK);
            // check if it is a Saturday or Sunday
                   if (day == Calendar.WEDNESDAY || day == Calendar.FRIDAY || day == Calendar.SATURDAY) {
                        // print the day - but you could add them to a list or whatever
                       //System.out.println(cal.get(Calendar.DAY_OF_MONTH));
                        System.out.println(simpleDateFormat.format(cal.getTime()));
                   }
            // advance to the next day
           cal.add(Calendar.DAY_OF_YEAR, 1);
         }  while (cal.get(Calendar.MONTH) == month);
        // stop when we reach the start of the next month
         }
}