Calculating Working Days Between Two Dates in Java.

Here is the code:

import java.util.*;
import java.text.*;
/*Author: Priyanka Kapoor
Date: 6th August,2012
Description:This program calculates working days between two dates.
*/
public class getdays{
public static int getdays(Date startDate, Date endDate) {
    Calendar startCal;
    Calendar endCal;
    startCal = Calendar.getInstance();
    startCal.setTime(startDate);
    endCal = Calendar.getInstance();
    endCal.setTime(endDate);
    int workDays = 0;
    //If working dates are same,then checking what is the day on that date.
    if (startCal.getTimeInMillis() == endCal.getTimeInMillis()) {
        if (startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY && startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY)
        {
            ++workDays;
        }
        }
    /*If start date is coming after end date, Then shuffling Dates and storing dates 
by incrementing upto end date in do-while part.*/
    if (startCal.getTimeInMillis() > endCal.getTimeInMillis()) {
            startCal.setTime(endDate);
            endCal.setTime(startDate);
    }

    do {
        
        if (startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY && startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
            ++workDays;
            }
    startCal.add(Calendar.DAY_OF_MONTH, 1);
        } while (startCal.getTimeInMillis() <= endCal.getTimeInMillis());

       return workDays; 
}

public static void main(String args[])

{
    String date1 = "2012-07-13";
    String date2 = "2012-07-16";
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    try{
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(format.parse(date1));
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(format.parse(date2));
        int workDays=getdays(cal1.getTime(),cal2.getTime());
        System.out.println("Total working Days = "+workDays);
    }
    catch(ParseException ex)
    {ex.printStackTrace();
    }

}//end main function
}//end class

Compile by:

 $javac getdays.java

Run by:

 $java getdays

 

 

Advertisements

About Priyanka Kapoor

Simple, Hardworking & friendly.....
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s