How can I find the dates of all the weekend days in a year?

Byron Tymvios

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

import java.text.SimpleDateFormat;

public class WeekendFinder{
	private Calendar cal = null;
	private int year = -1;
	private ArrayList weekendList = null;
	public WeekendFinder(int year){
		this.year = year;
		cal = Calendar.getInstance();
                  // Sets the date to the 1st day of the 1st month of the specified year
			cal.setTime(new SimpleDateFormat("dd/MM/yyyy").parse("01/01/" + this.year));
		}catch(java.text.ParseException e){
			System.err.println("Error parsing date: " + e.getMessage());
		weekendList = new ArrayList(53);

	public void findWeekends(){
            // The while loop ensures that you are only checking dates in the specified year
		while(cal.get(Calendar.YEAR) == this.year){
                  // The switch checks the day of the week for Saturdays and Sundays
				case Calendar.SATURDAY:
				case Calendar.SUNDAY:
                  // Increment the day of the year for the next iteration of the while loop
			cal.add(Calendar.DAY_OF_YEAR, 1);
      // Convenience method which just displays the contents of the ArrayList to the console
	public void displayWeekends(){
		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
		for(int i = 0; i < weekendList.size(); i++){
			System.out.println("WEEKEND: " + sdf.format((Date)weekendList.get(i)));

	public static void main(String[] args){
            // The program requires one argument of a year, so for example you could run the program with "java WeekendCalculator 2006"
		WeekendFinder wf = new WeekendFinder(Integer.parseInt(args[0]));

This code can be modified to find all weekdays in a year quite easily.

0 Comments  (click to add your comment)
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



About | Sitemap | Contact