Robin
Robin

Reputation: 1

How to set different hours for different days using Java Calendar?

I'm trying to create a simple Agenda class in order to set opening and closing hours for a shop. I want to set different hours depending on the day, so I'm using 2 Gregorian Calendars like this :

Here's my Agenda class :

private SimpleDateFormat openingFormatter = new SimpleDateFormat("EEEE yyyy.MM.dd ' - Your shop is opening at' HH:mm");
private SimpleDateFormat closingFormatter = new SimpleDateFormat(" 'and closing at' HH:mm'.'");
private GregorianCalendar openingHoursCalendar = new GregorianCalendar();
private GregorianCalendar closingHoursCalendar = new GregorianCalendar();
private int totalDays=365;


Agenda(){
    Calendar c = Calendar.getInstance();

    if (openingHoursCalendar.isLeapYear(c.get(Calendar.YEAR))) {
        totalDays++;
    }

    for(int d=1; d<=totalDays; d++) {

        openingHoursCalendar.set(Calendar.DAY_OF_YEAR,d);
        closingHoursCalendar.set(Calendar.DAY_OF_YEAR,d);

        if(openingHoursCalendar.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY){

            openingHoursCalendar.set(Calendar.HOUR_OF_DAY,8);
            openingHoursCalendar.set(Calendar.MINUTE, 0);

            closingHoursCalendar.set(Calendar.HOUR_OF_DAY,19);
            closingHoursCalendar.set(Calendar.MINUTE, 30);
        }

        else {

            openingHoursCalendar.set(Calendar.HOUR_OF_DAY,1);
            openingHoursCalendar.set(Calendar.MINUTE, 1);

            closingHoursCalendar.set(Calendar.HOUR_OF_DAY,1);
            closingHoursCalendar.set(Calendar.MINUTE, 1);
        }

    }
}

public void printFullAgenda(){

    openingHoursCalendar.add(Calendar.YEAR,-1);
    closingHoursCalendar.add(Calendar.YEAR,-1);

    for(int i=0; i<totalDays; i++){

        openingHoursCalendar.add(Calendar.DAY_OF_YEAR,1);
        closingHoursCalendar.add(Calendar.DAY_OF_YEAR,1);

        System.out.print(openingFormatter.format(openingHoursCalendar.getTime()));
        System.out.println(closingFormatter.format(closingHoursCalendar.getTime()));
    }
}

So I expected to print the same opening and closing hours for the Sundays (1:01) and 8:00 / 19:30 for the other days, but what I got instead was exactly the same hours for all days ("Your shop is opening at 08:00 and closing at 19:30."). I really don't get why. Can someone help me with this please.

Thanks

Upvotes: 0

Views: 63

Answers (0)

Related Questions