简体   繁体   中英

Setting Gregorian Calendar But Not Getting Correct Day of Week

In part of my program, I am manipulating the Gregorian Calendar by setting the date to what the user specifies. I am able to print the correct month, day, and year, but it is not showing the correct day of the week. Could someone please point out what is going on?

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Scanner;
import java.util.Map.Entry;


public class MyCalendar {

    GregorianCalendar calendar;
    private HashMap<GregorianCalendar, Event> myCalHash;
    GregorianCalendar dayCounter = new GregorianCalendar(); // capture today
    Scanner sc = new Scanner(System.in);
    static MONTHS[] arrayOfMonths = MONTHS.values();
    static DAYS[] arrayOfDays = DAYS.values();

    MyCalendar(){
        calendar = new GregorianCalendar();
        myCalHash = new HashMap<GregorianCalendar, Event>();
    }

    public HashMap<GregorianCalendar, Event> getMyCalHash(){
        return myCalHash;
    }

    public void setMyCalHash(HashMap<GregorianCalendar, Event> myCalHash) {
        this.myCalHash = myCalHash;
    }

    public void viewCalendar() {

            System.out.print("[D]ay view or [M]view? ");
            char userChoice = sc.next().charAt(0);
            if(Character.toUpperCase(userChoice) == 'D'){ dayView(); }
            else if(Character.toUpperCase(userChoice) == 'M'){ monthView(); }
            else{
                System.out.println("Invalid choice.");
            }
    }   

        public void dayView(){
            //print day calendar
            //GregorianCalendar dayCounter = new GregorianCalendar(); // capture today

            System.out.println(arrayOfDays[calendar.get(Calendar.DAY_OF_WEEK) - 1] + ", " +  arrayOfMonths[calendar.get(Calendar.MONTH)] 
                    + " " + calendar.get(Calendar.DATE) + ", " + calendar.get(Calendar.YEAR));
            System.out.print("[P]revious or [N]ext or [M]ain menu ? ");
            char userChoice = sc.next().charAt(0);
            if(Character.toUpperCase(userChoice) == 'P'){
                calendar.add(Calendar.DAY_OF_MONTH, -1);
                dayView();
            }
            else if(Character.toUpperCase(userChoice) == 'N'){
                calendar.add(Calendar.DAY_OF_MONTH, 1);
                dayView();
            }
            else if(Character.toUpperCase(userChoice) == 'M'){
                return;
            }
            else{
                System.out.println("Invalid choice.");
                return;
            }
        }
        public void monthView(){
            //print month calendar
            int formatCounter = 0;
            dayCounter.set(Calendar.DAY_OF_MONTH, 1);

            System.out.println("    " + arrayOfMonths[calendar.get(Calendar.MONTH) ] + " " + calendar.get(Calendar.YEAR)); //prints the month and year

            for(int i = 0; i < arrayOfDays.length; i++){
                if(i == 0){
                    System.out.print(arrayOfDays[i]);
                }
                else{
                    System.out.print(" " + arrayOfDays[i]);
                }
            }//print days of week

            System.out.println();
            for(int i = 0; i < arrayOfDays.length; i++){
                if(!arrayOfDays[i].equals(arrayOfDays[dayCounter.get(Calendar.DAY_OF_WEEK) - 1])){
                    System.out.print("   ");
                    formatCounter++;
                }
                else{
                    System.out.print(" " + calendar.getActualMinimum(Calendar.DAY_OF_MONTH) + " ");
                    formatCounter++;
                    break;
                }
            }

            for(int i = 1; i < dayCounter.getActualMaximum(Calendar.DAY_OF_MONTH); i++){
                if(formatCounter == 7){
                    System.out.println();
                    formatCounter = 0; //reset counter
                }
                dayCounter.roll(Calendar.DAY_OF_MONTH, true);
                if(dayCounter.get(Calendar.DATE) <= 9){
                    System.out.print(" " + dayCounter.get(Calendar.DATE) + " ");
                    formatCounter++;
                }
                else{
                    System.out.print(dayCounter.get(Calendar.DATE) + " ");
                    formatCounter++;
                }


            }

            System.out.print("\n[P]revious or [N]ext or [M]ain menu ? ");
            char userChoice = sc.next().charAt(0);
            if(Character.toUpperCase(userChoice) == 'P'){
                calendar.add(Calendar.MONTH, -1);
                dayCounter.add(Calendar.MONTH, -1);
                monthView();
            }
            else if(Character.toUpperCase(userChoice) == 'N'){
                calendar.add(Calendar.MONTH, 1);
                dayCounter.add(Calendar.MONTH, 1);
                monthView();
            }
            else if(Character.toUpperCase(userChoice) == 'M'){
                return;
            }
            else{
                System.out.println("Invalid choice.");
                return;
            }
        }


    public void goTo(){
        System.out.print("Enter a date in MM/DD/YYYY format: ");
        String userDate = sc.nextLine();
        String[] dateArr = userDate.split("/");
           calendar.set(GregorianCalendar.YEAR, Integer.parseInt(dateArr[2]));
           calendar.set(GregorianCalendar.MONTH, Integer.parseInt(dateArr[0]));
           calendar.set(GregorianCalendar.DATE, Integer.parseInt(dateArr[1]));

           System.out.println(arrayOfDays[calendar.get(Calendar.DAY_OF_WEEK) - 1] + ", " +  
           arrayOfMonths[calendar.get(Calendar.MONTH) - 1] + " " + calendar.get(Calendar.DATE) + ", " + calendar.get(Calendar.YEAR));

  //more stuff

    }



}

Edit: DAYS is an enum defined in a testerClass as follows:

    enum DAYS
{
    Su, Mo, Tu, We, Th, Fr, Sa;
}

Sample output: If user enters today's date (03/12/2015) Program should print: Th, March 12, 2015 But program is printing: Su, March 12, 2015

Another edit Here is how my months are defined in an enum:

enum MONTHS
{
    January, February, March, April, May, June, July, August, September, October, November, December;
}

Calendar month numbers are zero-based, so for instance, Calendar.MARCH == 2 . Your goTo() method does not account for that, and as a result, it sets the calendar to the wrong month.

Update :

It looks like you want this:

public void goTo(){
    System.out.print("Enter a date in MM/DD/YYYY format: ");
    String userDate = sc.nextLine();
    String[] dateArr = userDate.split("/");

    calendar.set(GregorianCalendar.YEAR, Integer.parseInt(dateArr[2]));
    calendar.set(GregorianCalendar.MONTH, Integer.parseInt(dateArr[0]) - 1);
    calendar.set(GregorianCalendar.DATE, Integer.parseInt(dateArr[1]));

    System.out.println(arrayOfDays[calendar.get(Calendar.DAY_OF_WEEK) - 1] + ", "
            + arrayOfMonths[calendar.get(Calendar.MONTH)] + " "
            + calendar.get(Calendar.DATE) + ", "
            + calendar.get(Calendar.YEAR));
    // ...
}

John Bollinger's answer points out the reason why you're seeing this anomaly, due to the fact that the months are 0-based, not 1-based, and your goTo method is setting the date incorrectly.

There's a couple issues here, that are giving you the false impression that you've set something up correctly everywhere except the day of week.

First:

calendar.set(GregorianCalendar.MONTH, Integer.parseInt(dateArr[0]));

You parse the user input and set the month of the calendar based on the user value (aka 03 for "March").

However, as John has pointed out, the month numbers are 0-based, so the calendar thinks 3 is "April".

This is all well and good for your lookup, as you're properly getting the day of week (Sunday), but for the wrong month (April), on day 12 in 2015.

Your lookup from the array though is properly giving you the impression that the Month is set right because you're using the Calendar's value for the month (which is 0 based).

You are incorrectly subtracting 1 from this value to look up the Month name, which makes you think that the day of week is wrong.

You need to fix two places (lookup and set):

calendar.set(GregorianCalendar.YEAR, Integer.parseInt(dateArr[2]));
calendar.set(GregorianCalendar.MONTH, Integer.parseInt(dateArr[0])-1);
calendar.set(GregorianCalendar.DATE, Integer.parseInt(dateArr[1]));

System.out.println(arrayOfDays[calendar.get(Calendar.DAY_OF_WEEK) - 1] + ", " +  
arrayOfMonths[calendar.get(Calendar.MONTH)] + " " + calendar.get(Calendar.DATE) + ", " + calendar.get(Calendar.YEAR));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM