开发者

Find all Saturday and Sunday from given date range

开发者 https://www.devze.com 2023-04-12 07:55 出处:网络
I want to take all Saturday and Sunday from given date r开发者_开发技巧ange... my inputs are Start Date : 01/01/2011

I want to take all Saturday and Sunday from given date r开发者_开发技巧ange...

my inputs are

Start Date : 01/01/2011 End Date : 01/01/2012

now search date which is in between given start date and end date and day would be Saturday or Sunday.

Please Suggest...


Firstly, I'd recommend using Joda Time if you possibly can. It's a much better date and time API than the one built into Java.

Secondly, unless you're really worried about efficiency I would personally go for the incredibly-simple-but-somewhat-wasteful approach of simply iterating over every day in the time period, and including those which fall on the right days. Alternating between adding one day and adding six days would certainly be more efficient, but harder to change.

Sample code:

import java.util.*;
import org.joda.time.*;

public class Test
{
    public static void main(String[] args)
    {
        List<LocalDate> dates = getWeekendDates
            (new LocalDate(2011, 1, 1), new LocalDate(2011, 12, 1));
        for (LocalDate date : dates)
        {
            System.out.println(date);
        }
    }

    private static List<LocalDate> getWeekendDates
        (LocalDate start, LocalDate end)
    {
        List<LocalDate> result = new ArrayList<LocalDate>();
        for (LocalDate date = start;
             date.isBefore(end);
             date = date.plusDays(1))
        {
            int day = date.getDayOfWeek();
            // These could be passed in...
            if (day == DateTimeConstants.SATURDAY ||
                day == DateTimeConstants.SUNDAY)
            {
                result.add(date);
            }
        }
        return result;
    }                                            
}


I recommend to take a look at this RFC-2445 Java open-source library. You can create a weekly recurrence rule with repeating on Sat and Sun, then iterate over the specified period to get all dates.


I think, you can use following way - it's really simple and you don't need to use other libraries.

Take weekday number (for Monday = 1, Sunday = 7). Then - choose new start date, which is first Sunday occurence -> it is startDate + (7 - weekdayNum). By the same algorithm, you can take last Sunday from interval (by substracting EndDate - weekdayNum - 1, I think). And now you can go in for loop through all occurences (use incremental step 7). Or if you want specific occurence, e.g. 3rd sunday, you can simply do newStartDate + 3 * 7.

I hope, this is clear. I'm not sure, if numbers are correct. Hope this helps for understanding the problem.


Here is the complete example. Please do suggest if we can make it better.

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 
 * @author varun.vishwakarma
 */
public class FindWeekendsInDateRange {
static HashMap<Integer, String> daysOfWeek=null;


static {
	daysOfWeek = new HashMap<Integer, String>();
	daysOfWeek.put(new Integer(1), "Sun");
	daysOfWeek.put(new Integer(2), "Mon");
	daysOfWeek.put(new Integer(3), "Tue");
	daysOfWeek.put(new Integer(4), "Wed");
	daysOfWeek.put(new Integer(5), "Thu");
	daysOfWeek.put(new Integer(6), "Fri");
	daysOfWeek.put(new Integer(7), "Sat");
}

/**
 * 
 * @param from_date 
 * @param to_date
 * @return 
 */
public static List<Date>  calculateWeekendsInDateReange(Date fromDate, Date toDate) {
	List<Date> listOfWeekends = new ArrayList<Date>();
		Calendar from = Calendar.getInstance();
		Calendar to = Calendar.getInstance();
		from.setTime(fromDate);
		to.setTime(toDate);
		while (from.getTimeInMillis() < to.getTimeInMillis()) {
			if (daysOfWeek.get(from.get(Calendar.DAY_OF_WEEK)) == "Sat") {
				Date sat = from.getTime();
				listOfWeekends.add(sat);
			} else if (daysOfWeek.get(from.get(Calendar.DAY_OF_WEEK)) == "Sun") {
				Date sun = from.getTime();
				listOfWeekends.add(sun);
			}
			from.add(Calendar.DAY_OF_MONTH, 1);
		}
	return listOfWeekends;
}
public static void main(String[] args) {
	String fromDate = "7-Oct-2019";
	String toDate = "25-Oct-2019";
	System.out.println(FindWeekendsInDateRange.calculateWeekendsInDateReange(new Date(fromDate), new Date(toDate)));


}

}


I'm assuming your start and end dates are given in milliseconds. Loop through the dates and check whether days are 'Saturday' or 'Sunday'. Below I'm returning the total no. of Saturday and Sunday in given date range.

private int totalWeekendDays(long start, long end)
{
    int result=0;
    long dayInMS = TimeUnit.DAYS.toMillis(1);
    for (long i = start; i<=end; i = i + dayInMS)
    {
        String dayOfTheWeek = (String) DateFormat.format("EEEE", i);
        if (dayOfTheWeek.equals("Sunday")||dayOfTheWeek.equals("Saturday"))
        {
            result = result+1;
        }
    }
    return result;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号