Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 18 of 18

Thread: How can I determine what day of the week a given month falls on in Java without using the Calendar Object?

  1. #1
    Junior Member
    Join Date
    Nov 2018
    Posts
    9
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default How can I determine what day of the week a given month falls on in Java without using the Calendar Object?

    I'm creating a Calendar for my CS class and need to be able to get my calendar months to start on the correct day of the week. My first go at trying to solve this problem looked something like this:
    public static int getStartingDay(int month) {
     
    if (month == 1 || month == 10) {
     
    return (22) % 7;
     
    } else if (month == 2 || month == 3 || month == 11) {
     
    return ((25)) % 7;
     
    } else if (month == 4 || month == 7) {
     
    return ((28)) % 7;
     
    } else if (month == 9 || month == 12) {
     
    return ((27) % 7);
     
    } else if (month == 5) {
     
    return ((23) % 7);
     
    } else {
     
    return ((23) % 7);
     
    }
    I was really happy to see that this was working but when I showed this to my teacher he said that it could be done in a much simpler way.

    He responded:

    "First of all, I want you to recall that I stated we are just concerned with 2018. Therefore, we only need to know what day 2018 started on. From there, we can basically do what we did for the second writing code question on the midterm, where given a day out of 365 for the year, we can determine what day of the week that falls on. This means that all we have left to do it determine what day out of 365 that a given month falls on. This can be done with some addition if we know how many days are in each month. We can just add up all of the previous month's days to get what day our month starts on. "

    For the midterm, we were to assume that the year started on Wednesday (3rd day of the week) so my solution looked like this:

    Method call : dayOfYear(5); Should return: 0 for Sunday
    Public static final int FIRST_DAY_OF_YEAR = 3;
    Public static int dayOfTheWeek(int day){
    return (firstDay + day –1)%7;
    }
    Result: 0 (Sunday)

    I'm a bit lost on how these two problems are connected. I know the key in my teacher's response was:

    "This means that all we have left to do it determine what day out of 365 that a given month falls on." If you could help me understand how to solve this problem, you would be helping me tremendously!

    I should also add, We are not allowed to use Java's Calendar object to get this working properly!

    Here is my current Project:
    import java.util.*;
    public class CalendarReformed {
        // Here we can change the size of the calendar
        public static final int FIRST_DAY_OF_MONTH = 1;
        private static final int SIZE =  7;
     
        public static void main(String[] args){
            Scanner console = new Scanner(System.in);
            int day = -1;
            int month = -1;
            String userSelection;
            boolean flag = true;
     
            while (flag){
     
                userMenu();
                userSelection = console.next();
                if (userSelection.equalsIgnoreCase("e")){
                    System.out.print("Please enter a date:(mm/dd) ");
                    String date = console.next();
                    month = monthFromDate(date);
                    day = dayFromDate(date);
                    int highlightSelectedDay = day;
                    displayCalendar(month, highlightSelectedDay);
     
                } else if (userSelection.equalsIgnoreCase("t")){
                    Calendar c = Calendar.getInstance();
                    day = c.get(Calendar.DATE);
                    month = c.get(Calendar.MONTH)+1;
                    System.out.println("Today's date: " + month +"/"+ day);
                    displayCalendar(month,day);
                } else if (userSelection.equalsIgnoreCase("n")){
                    if (day != -1 && month != -1){
                        day = 1;
     
                        month = grabNextMonth(month);
                        displayCalendar(month,day);
                    } else{
                        System.out.print("You must have a month selected to go to next month!\n");
                    }
                } else if(userSelection.equalsIgnoreCase("p")){
                    if (day != -1 && month != -1){
                        day = 1;
     
                        month = grabPreviousMonth(month);
                        displayCalendar(month, day);
                    } else {
                        System.out.print("You must first select a month for previous month to function!\n");
                    }
                } else if(userSelection.equalsIgnoreCase("q")){
                    System.out.print("Now exiting the Calendar program\n");
                    System.out.print("Have a nice day!");
                    flag = false;
                } else {
                    System.out.print("        *USER ERROR DETECTED*    \n");
                    System.out.println("Please make a valid selection from the menu!");
                }
            }
     
        }
     
        // This method will print the month digit and centers it
        public static void drawMonth(int month, int daysToSkip, int maxDays){
            System.out.println();
            int placeMonth = (SIZE * 3)-4;
            for (int space = 1; space <= placeMonth; space++){
                printSpaces(1);
            }
            String monthHolder;
            if (month == 1){
                monthHolder = "*January*";
            } else if(month == 2){
                monthHolder = "*February*";
            }else if (month == 3){
                monthHolder = "*March*";
            } else if (month == 4){
                monthHolder = "*April*";
            } else if (month == 5){
                monthHolder = "*May*";
            } else if (month == 6){
                monthHolder = "*June*";
            } else if (month == 7){
                monthHolder = "*July*";
            } else if (month == 8){
                monthHolder = "*August*";
            } else if (month == 9){
                monthHolder = "*September*";
            } else if (month == 10){
                monthHolder = "*October*";
            } else if (month == 11){
                monthHolder = "*November*";
            } else {
                monthHolder = "*December*";
            }
            System.out.println(monthHolder);
     
            drawArt();
     
                int start = 1;
                while (start <= maxDays) {
                    if (start == 1) {
                        drawRow(start, maxDays, daysToSkip);
                        start += 7 - daysToSkip;
                    } else {
                        drawRow(start, maxDays, 0);
                        start += 7;
                    }
                }
     
            // Displays the top of the calendar border
            for (int i = 1; i <= SIZE * 7; i++){
                System.out.print("_");
            }
        }
     
        // This method prints one row of our calendar and applies our | dividers
        public static void drawRow(int start,int maxDays, int skip){
                for (int top = 1; top <= SIZE * 7; top++){
                    System.out.print("_");
                }
                System.out.println();
     
                int printDayNum = start;
                String dayTool;
     
                System.out.print("|");
            int highlightSelectedDay = -1;
            for (int i = 1; i <= 7; i++) {
                dayTool = "";
                if (i > skip && printDayNum <= maxDays) {
                    if (highlightSelectedDay == printDayNum) {
                        dayTool += " ->" + printDayNum++ + "*";
                    } else {
                        dayTool += printDayNum++;
                    }
                }
     
                while (dayTool.length() < SIZE - 1){
                    dayTool += " ";
            }
     
                    dayTool += "|";
                System.out.print(dayTool);
            }
            int height = SIZE /2;
            for (int h = 2; h <= height; h++){
                System.out.print("\n|");
                for (int cell = 1; cell <= 7; cell++){
                    dayTool = "";
                    while (dayTool.length() < SIZE -1) {
                        dayTool += " ";
                    }
                    dayTool+="|";
                    System.out.print(dayTool);
                }
            }
            System.out.println();
        }
     
     
        // This method will display month and the day under the calendar
        public static void displayDate(int month, int day){
            System.out.println();
            System.out.println("Month: " + month);
            System.out.println("Day: " + day);
        }
     
        // This method grabs the month string from the user input and returns it as an integer
        public static int monthFromDate( String date){
            int index = date.indexOf("/");
            String month = date.substring(0,index);
            return Integer.parseInt(month);
        }
     
     
        public static void dateError(String prompt){
            System.out.print(prompt+"\n");
        }
        // This method grabs the date which is always after the first two spots of the user date String Returns an int
        public static int dayFromDate(String date) {
            int index = date.indexOf("/");
            String day = date.substring(index + 1);
            return Integer.parseInt(day);
     
        }
        // Handles the ASCII art above calendar
        public static void pattern(){
            for (int i = 1; i <= 49/6; i++){
                System.out.print("\\ 0 / ");
            }
            System.out.println();
            for (int i = 1; i <=49/6; i++){
                System.out.print("<(.)> ");
            }
            System.out.println();
            for (int i = 1; i <= 49/6; i++){
                System.out.print("/ + \\ ");
            }
            System.out.println();
        }
     
        public static void displayCalendar(int month, int day) {
            int startDay = getStartingDay(month);
            int maxDaysInMonth = getMaxDays(month);
            drawMonth(month, startDay, maxDaysInMonth);
            displayDate(month,day);
        }
     
        public static int getStartingDay(int month) {
            if (month == 1 || month == 10) {
                return (22) % 7;
            } else if (month == 2 || month == 3 || month == 11) {
                return ((25)) % 7;
            } else if (month == 4 || month == 7) {
                return ((28)) % 7;
            } else if (month == 9 || month == 12) {
                return ((27) % 7);
            } else if (month == 5) {
                return ((23) % 7);
            } else {
                return ((23) % 7);
            }
     
        }
            public static int getMaxDays(int month){
            int numberOfDays;
            if (month == 4 || month == 6 || month == 9 || month == 11){
                numberOfDays = 30;
            } else if (month == 2){
                numberOfDays = 29;
            } else
                numberOfDays = 31;
            return numberOfDays;
        }
     
        public static int grabNextMonth(int currentMonth) {
            if (currentMonth == 12) // if current month is december
            {
                return 1; // lets give the user January
            } else
                return currentMonth + 1; // rest of the time just display the next month
        }
        public static int grabPreviousMonth(int currentMonth){
            if (currentMonth == 1){
                return 12;
            } else
                return currentMonth - 1;
        }
     
        // A little more art for top of calendar
        public static void drawArt(){
            System.out.println(" ____   ___ _      ____ ____  ____|  ___   ____       ");
            System.out.println("|      /__ \\ |    |____|    ||    | /__ \\ |    \\      ");
            System.out.println("|____ /     \\|____|____|    ||__ _|/     \\|          ");
            printChars('_',48);
            System.out.println();
            for (int i = 1; i <= 2; i+=2){
                pattern();
            }
        }
     
        public static void userMenu(){
            System.out.println("Please enter a command: ");
            System.out.println("\t\t[\"e\"] to enter a date and display it");
            System.out.println("\t\t[\"t\"] to get today's date and display the corresponding calendar");
            System.out.println("\t\t[\"n\"] to display the next month");
            System.out.println("\t\t[\"p\"] to display the previous month");
            System.out.println("\t\t[\"q\"] to quit the program");
        }
     
        // Method that prints desired chars whenever called
        public static void printChars(char ch, int num){
            for (int i = 1; i <= num; i++){
                System.out.print(ch);
            }
        }
     
        // Method that can printSpaces when called
        public static void printSpaces(int num){
            for (int i = 1; i <= num; i++){
                System.out.print(" ");
            }
        }
     
    }

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: How can I determine what day of the week a given month falls on in Java without using the Calendar Object?

    what day of the week a given month falls on
    Are you asking what DoW the first day in a month in a given year starts on?
    For example Nov 1978 starts on a Wednesday.

    First work out the algorithm, then write the code based on that.
    If you don't understand my answer, don't ignore it, ask a question.

  3. The Following User Says Thank You to Norm For This Useful Post:

    WashingtonBrewologist (November 10th, 2018)

  4. #3
    Junior Member
    Join Date
    Nov 2018
    Posts
    9
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default Re: How can I determine what day of the week a given month falls on in Java without using the Calendar Object?

    I have no idea where to begin with this algorithm. Do you have any sugestions?

  5. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: How can I determine what day of the week a given month falls on in Java without using the Calendar Object?

    What is the program's input? For example Month and year?
    What is a data point that anchors the calendar? A DoW for a given Month and year. For example: Nov 1978 starts on a Wednesday.
    If you don't understand my answer, don't ignore it, ask a question.

  6. The Following User Says Thank You to Norm For This Useful Post:

    WashingtonBrewologist (November 10th, 2018)

  7. #5
    Junior Member
    Join Date
    Nov 2018
    Posts
    9
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default Re: How can I determine what day of the week a given month falls on in Java without using the Calendar Object?

    The user will enter a date with the following format (dd/mm) and it will display the calendar. Here is an example of what the console looks like when I run the program:

    Please enter a command:
    ["e"] to enter a date and display it
    ["t"] to get today's date and display the corresponding calendar
    ["n"] to display the next month
    ["p"] to display the previous month
    ["q"] to quit the program
    e
    Please enter a date(mm / dd): 01/02

    [Here the calendar is displayed]

    --- Update ---

    I believe for this calendar the Anchor would be Jan 1st 2018 which starts on a monday the first day of the week. Sun: 0, mon:1 , tues:2.. and so on.

  8. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: How can I determine what day of the week a given month falls on in Java without using the Calendar Object?

    That doesn't answer my questions. Your user input does not have the year for month to display.
    To be able to find the DoW that a selected month in a year starts on I think you need a base date to work from and the year of the month to display.
    Given that base then some minor and modulus arithmetic should help find the DoW.
    If you don't understand my answer, don't ignore it, ask a question.

  9. The Following User Says Thank You to Norm For This Useful Post:

    WashingtonBrewologist (November 10th, 2018)

  10. #7
    Junior Member
    Join Date
    Nov 2018
    Posts
    9
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default Re: How can I determine what day of the week a given month falls on in Java without using the Calendar Object?

    I'm not quite understanding what your asking. This calendar should only be displaying the correct days for the 2018 calendar year.
    My first solution which I will post again below was not what my teacher had in mind for the method. He said we only need to be concerned with 2018. And that I should be able to add up the days from the previous months to get the correct start day.
    previous solution:
    public static int getStartingDay(int month) {
     
    if (month == 1 || month == 10) {
     
    return (22) % 7;
     
    } else if (month == 2 || month == 3 || month == 11) {
     
    return ((25)) % 7;
     
    } else if (month == 4 || month == 7) {
     
    return ((28)) % 7;
     
    } else if (month == 9 || month == 12) {
     
    return ((27) % 7);
     
    } else if (month == 5) {
     
    return ((23) % 7);
     
    } else {
     
    return ((23) % 7);

    How can I use the fact that the first day of the year: Jan 1st 2018 starts on a monday which is day 1 of the week, to display the next months correct starting days of the week?

  11. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: How can I determine what day of the week a given month falls on in Java without using the Calendar Object?

    Ok, so only for 2018 and Jan 2018 starts on Monday.
    to display the next months correct starting
    To get the DoW for Feb 1, use modulus 7 on the days in January and add that to Monday. Continue month by month to the desired month.
    If you don't understand my answer, don't ignore it, ask a question.

  12. The Following User Says Thank You to Norm For This Useful Post:

    WashingtonBrewologist (November 10th, 2018)

  13. #9
    Junior Member
    Join Date
    Nov 2018
    Posts
    9
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default Re: How can I determine what day of the week a given month falls on in Java without using the Calendar Object?

    When you say "add it to Monday" do you mean: take the result of modding days of Jan by 7, and add this to 1?

    If the month is 1
    startday is one
    if not
    mod days of previous month by seven
    add result to Mon(1st)?

  14. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: How can I determine what day of the week a given month falls on in Java without using the Calendar Object?

    When you say "add it to Monday" do you mean: take the result of modding days of Jan by 7, and add this to 1?
    Yes.
    If you don't understand my answer, don't ignore it, ask a question.

  15. The Following User Says Thank You to Norm For This Useful Post:

    WashingtonBrewologist (November 10th, 2018)

  16. #11
    Junior Member
    Join Date
    Nov 2018
    Posts
    9
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default Re: How can I determine what day of the week a given month falls on in Java without using the Calendar Object?

    I'm having trouble trying to figure out how to properly loop through the months and while doing so, also summing their days. Do you know how I could accomplish this? I know something is off in the way I'm thinking about this and i can't seem to pinpoint why I can't figure it out.
    for (each of 12 months)
    if i = month
    sum all of the previous months days and mod by 7
    add result to sum of previous days...
    return the result

  17. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: How can I determine what day of the week a given month falls on in Java without using the Calendar Object?

    loop through the months and while doing so, also summing their days.
    Put the days/month in a 12 element array. If past Feb add 1 for leap year
    Or have put accumulative days in array to save having to sum them.
    If you don't understand my answer, don't ignore it, ask a question.

  18. The Following User Says Thank You to Norm For This Useful Post:

    WashingtonBrewologist (November 10th, 2018)

  19. #13
    Junior Member
    Join Date
    Nov 2018
    Posts
    9
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default Re: How can I determine what day of the week a given month falls on in Java without using the Calendar Object?

    I'm not allowed to use arrays yet. We are only allowed to use material from the first 5 chapters of our book which limits the possible solutions for this problem. Any other Ideas?
    By the way thank you for your help! I have been at this all day and it's been driving me crazy!

  20. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: How can I determine what day of the week a given month falls on in Java without using the Calendar Object?

    How about a list of if statements that adds the days in month to a total depending on if selected month is greater than this month's id.
    Can you use the accumulated number of days in the program? For example for March it would be 31+28+31
    If you don't understand my answer, don't ignore it, ask a question.

  21. #15
    Junior Member
    Join Date
    Nov 2018
    Posts
    9
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default Re: How can I determine what day of the week a given month falls on in Java without using the Calendar Object?

    Yes! I believe that would be ok.
    do you mean something like this:
    if (month == 3)
    total = 90; // 31+28+31
    if (month == 4)
    total = 120 // 31 + 28 + 31 + 30

  22. #16
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: How can I determine what day of the week a given month falls on in Java without using the Calendar Object?

    do you mean something like this:
    Yes,
    If you don't understand my answer, don't ignore it, ask a question.

  23. #17
    Junior Member
    Join Date
    Nov 2018
    Posts
    9
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default Re: How can I determine what day of the week a given month falls on in Java without using the Calendar Object?

    So i've created the if statements that give a total to each individual month. Now how can I reach into the previous months if branch to pull out the total to sum?
     int total = 0;
                if (month == 1) {
                    total = 31;
                } else if (month == 2) {
                    total = 59;
                } else if (month == 3) {
                    total = 90;
                } else if (month == 4) {
                    total = 120;
                } else if (month == 5) {
                    total = 151;
                } else if (month == 6) {
                    total = 181;
                } else if (month == 7) {
                    total = 212;
                } else if (month == 8) {
                    total = 243;
                } else if (month == 9) {
                    total = 273;
                } else if (month == 10) {
                    total = 304;
                } else if (month == 11) {
                    total = 334;
                } else if (month == 12) {
                    total = 365;
                }

  24. #18
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: How can I determine what day of the week a given month falls on in Java without using the Calendar Object?

    how can I reach into the previous months if branch to pull out the total to sum?
    Those statements will give you the days for the month. There is no need to do a sum.
    Create a method that returns the days for a month with those if statements.
    The valid months are 0 to 11. There isn't a month 12.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Problem with day of month code
    By Prinny in forum What's Wrong With My Code?
    Replies: 2
    Last Post: September 21st, 2014, 01:22 PM
  2. Help determining which day a particular date falls on.
    By Prox in forum What's Wrong With My Code?
    Replies: 2
    Last Post: November 7th, 2011, 11:49 PM
  3. Calendar.MONTH return wrong value
    By bczm8703 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: November 5th, 2011, 09:33 AM
  4. How to print the day of the week from user input?
    By f0x in forum Java Theory & Questions
    Replies: 2
    Last Post: October 31st, 2011, 05:33 PM
  5. Array month/day/hour/min/sec incomplete java code
    By mightyking in forum Collections and Generics
    Replies: 12
    Last Post: September 18th, 2011, 08:46 PM

Tags for this Thread