nuwan.danushka nuwan.danushka - 11 months ago 52
Java Question

Get week days getter

I want to get week days between two dates, return type should be string array which consist of week days such (''Sunday", "Monday"....etc) could you please help me to clarify this issue. i have no idea with this

As per my problem i want to get week days between start date end date as per below

SimpleDateFormat myFormat = new SimpleDateFormat("dd/MM/yyyy");
String startDate="01/07/2015";
String endDate="31/07/2015";
try {
Date sDate=myFormat.parse(startDate);
Date eDate=myFormat.parse(endDate);

} catch (ParseException e) {
// TODO Auto-generated catch block

Answer Source

First, try and find the difference in days between the start and end dates:

long startTime = sDate.getTime();
long endTime = eDate.getTime();
long differenceMillis = endTime - startTime;
// divide by the number of millis per day
int differenceInDays = Math.ceil((double) differenceMillis / MILLIS_PER_DAY);

Then, you can find on which day of the week does your interval start:

Calendar startCal = Calendar.getInstance();
// if you need to skip the actual start day from the interval, add a day to the calendar
int dayOfWeek = startCal.get(DAY_OF_WEEK);

After you have your start day of the week and the difference between the dates, you can loop and add the appropriate values to your resulting list:

List<String> days = new LinkedList<>();
for (int i = 0; i < differenceInDays; i++) {
    if (7 < dayOfWeek) {
        // if we have reached the last day of the week, we reset to the first day of the week
        dayOfWeek = 1;

    switch (dayOfWeek) {
        case Calendar.SATURDAY:
        // add other cases here

This should be the basic steps you need to follow. The code is just an example, you can optimise and adapt it to use the best practices.

Edit: Fixed a bug in the for loop - dayOfWeek should be incremented by one on each iteration, not by i. Now it should work OK.