[Math Lair] dayOfWeek.java

Math Lair Home > Interactive content > dayOfWeek.java
/* dayOfWeek.java
 *
 * Determines day of week given date.
 *
 * Written by A. James Yolkowski, 5/17/2000.
 * Algorithm taken from day_of_week.pl,
 * by Malcolm Beattie as posted in comp.lang.perl and in CPAN.
 */

import java.applet.*;
import java.awt.*;
import java.lang.*;

public class dayOfWeek extends Applet {

  TextField y, m, d;
  Label yLabel, mLabel, dLabel, dayOfWeekLabel;
  Button compute;

  public void init() {
    resize(360, 72);
    m = new TextField(2);
    d = new TextField(2);
    y = new TextField(4);
    compute = new Button("Compute");
    yLabel = new Label("Year: ");
    mLabel = new Label("Month: ");
    dLabel = new Label("Date: ");
    dayOfWeekLabel = new Label("                      ");
    add(dLabel); add(d);
    add(mLabel); add(m);
    add(yLabel); add(y);
    add(dayOfWeekLabel);
    add(compute);
    //    add(dayOfWeekLabel);
  }

  public void paint(Graphics g) {}

  public boolean action (Event e, Object O) {
    int date, month, year;
    int y2;
    int dow;
    int dinc[] = {0,3,2,5,0,3,5,1,4,6,2,4};
    String day[] = {"Sunday", "Monday", "Tuesday", "Wednesday",
		    "Thursday", "Friday", "Saturday"};
    String tempstr;

    // Parse the numbers from the day, month, and year fields.
    if(e.target instanceof Button) {
      tempstr = "0";
      tempstr = tempstr.concat(d.getText());
      date = Integer.parseInt(tempstr);

      tempstr = "0";
      tempstr = tempstr.concat(m.getText());
      month = Integer.parseInt(tempstr);

      tempstr = "0";
      tempstr = tempstr.concat(y.getText());
      year = Integer.parseInt(tempstr);

      y2 = year;
      if (month < 3) y2--;	// Account for leap years.
      dow = (y2 + (y2/4) - (y2/100) + (y2/400) + dinc[month-1] + date) %7;
      
      tempstr = "is a ";
      tempstr = tempstr.concat(day[dow]);
      dayOfWeekLabel.setText(tempstr);
    }
    return true;
  }
}