I have been using JAVA for a whole two weeks now. I am enrolled in CSC 148 at my local college.

I am supposed to write a program that asks the user for his or her age and replies with the day of the week on which he or she was born.

I am familiar with the I/O, but cannot figure out to convert from a date
(ie. 07/04/1776) to a day (ie. Saturday).

Here is my current code:

/*
     Ask the user for his or her birthdate and return with the day of the week
     on which he or she was born.
*/

import javax.swing.*;
import java.sql.*;  //For Return Date

class Exercise2_29 {

     public static void main( String[] args ) {

          //Input user birth date
          String          bdate;

          bdate = JOptionPane.showInputDialog(null, "What is your birth date?
                                                                    (MM/DD/YYYY)");

          //Convert user birth date to day of week

     }
}

Note: I can only use the java.util or java.sql classes. The GregorianCalendar class has not yet been officially taught and, therefore, can't be used.

Also, is the code I currently have good. Do I need to import any other classes, or add any more strings?

Thanks in advance for any help.

bcheath_1

Dani AI

Generated

’s input code and the replies show two routes: use the standard date classes (as noted) or do a day-count and mod 7 (as suggested). Because GregorianCalendar was off-limits in the assignment, a compact, library-free approach is Tomohiko Sakamoto’s algorithm — a tiny O(1) formula that returns the weekday from year/month/day without building a running total. See a clear description and rationale here: Tomohiko Sakamoto’s algorithm. (geeksforgeeks.org)

A minimal Java example (uses only javax.swing and primitive math):

import javax.swing.*;

public class BirthWeekday {
    public static void main(String[] args) {
        String input = JOptionPane.showInputDialog(null, "Enter birth date (MM/DD/YYYY):");
        if (input == null) return;
        String[] p = input.trim().split("/");
        if (p.length != 3) { JOptionPane.showMessageDialog(null, "Format must be MM/DD/YYYY"); return; }

        int m, d, y;
        try {
            m = Integer.parseInt(p[0]); d = Integer.parseInt(p[1]); y = Integer.parseInt(p[2]);
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(null, "Numeric values required"); return;
        }

        boolean leap = isLeap(y);
        int[] mdays = {31, leap?29:28, 31,30,31,30,31,31,30,31,30,31};
        if (m < 1 || m > 12 || d < 1 || d > mdays[m-1]) { JOptionPane.showMessageDialog(null, "Invalid date"); return; }

        int[] t = {0,3,2,5,0,3,5,1,4,6,2,4};
        int yy = (m < 3) ? y - 1 : y;
        int dow = (yy + yy/4 - yy/100 + yy/400 + t[m-1] + d) % 7; // 0=Sunday ... 6=Saturday
        String[] names = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};
        JOptionPane.showMessageDialog(null, "Day of week: " + names[dow]);
    }

    static boolean isLeap(int y) {
        return (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0);
    }
}

Validation notes and caveats: parse and validate the three numeric parts (MM, DD, YYYY) and check month/day ranges (February needs leap-year handling shown above). The Sakamoto formula assumes Gregorian calendar dates — for historical dates before local adoption of the Gregorian reform (different countries switched at different times) the weekday can differ; see a concise history of the Gregorian switch. (britannica.com)

If and when classroom rules permit using the Java date/time APIs, those built-ins handle parsing, locales and edge cases. Zeller’s congruence is an alternate algorithmic method worth reading about if more than one formulaic option is desired. (en.wikipedia.org)

Recommended Answers

All 4 Replies

install the API docs.
Look up DateFormat, SimpleDateFormat, java.util.Date, and Calendar.
Using those you can do what you want quite easily.

I'm a newbie, also, trying to figure out the same problem...and I'm still trying to figure out just how to use DateFormat, SimpleDateFormat, java.util.Date, and Calendar. It seems that the original post was trying to get an example of how you programatically determine the day of the week that a person was born on...Could someone provide a basic example of this?

Thanks,

count the days in between current date and that date, subtract it, mod it by 7

nah. Plug the date into a Calendar and get the correct field out of it...
Something like

Calendar calendar = new GregorianCalendar();
calendar.setTime(birthdate);
int dayOfBirth = calendar.get(Calendar.DAY_OF_WEEK);

The biggest mistake many beginners in Java (or most languages) seem to make is to not study the standard library.
It contains a TON of very handy utility classes that can really make your life easy.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.