Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

datetime - How to get every day except weekend or Saturday or Sunday between two dates in java?

hi all how to generate dates if the start date and end date are provided in java?

like the following :

Ex : if the start date is 15-04-2012 and end date is 15-06-2012 having this i want dates to be like the following and the list should omit saturday and sunday

1.15-04-2012, 2.16-04-2012, 3.17-04-2012, . . . . . . 15-06-2012

I have done like the following but it will generate for one month if the date range is of same month. `

public static ConcurrentHashMap<String, String> getWorkingDaysMap(int year, int month, int day){
        int totalworkingdays=0,noofdays=0;
        String nameofday = "";
        ConcurrentHashMap<String,String> workingDaysMap = new ConcurrentHashMap<String,String>();
        Map<String,String> holyDayMap = new LinkedHashMap<String,String>();
        noofdays = findNoOfDays(year,month,day);

        for (int i = 1; i <= noofdays; i++) {
            Date date = (new GregorianCalendar(year,month - 1, i)).getTime(); // year,month,day
            SimpleDateFormat f = new SimpleDateFormat("EEEE");
            nameofday = f.format(date);

            String daystr="";
            String monthstr="";

            if(i<10)daystr="0";
            if(month<10)monthstr="0";

            String formatedDate = daystr+i+"/"+monthstr+month+"/"+year;

            if(!(nameofday.equals("Saturday") || nameofday.equals("Sunday"))){
                workingDaysMap.put(formatedDate,formatedDate);
                totalworkingdays++;
            }
        }

        return workingDaysMap;
    }

So please do advice me how to go about.

Regards Tony

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
int noOfDaysBetween = 5;
Calendar cal  = Calendar.getInstance();
cal.setTime(startDate);

for(int index = 0 ; index < noOfDaysBetween; index++){
    int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
    if( dayOfWeek!=Calendar.SUNDAY && dayOfWeek!=Calendar.SATURDAY) {
        System.out.println(cal.getTime());
    }
    cal.add(Calendar.DATE, 1);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...