An algorithm for calculating the day of the week given a Date
Given a date and calculate day of the week:
import java.util.*;
public class Datetoday {
final static String[] WEEK_DAYS = {
"Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday"
};
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the date in dd/mm/yyyy form: ");
String[] partofdate = input.nextLine().split("/");
int d = Integer.parseInt(partofdate[0]);
int m = Integer.parseInt(partofdate[1]);
int y = Integer.parseInt(partofdate[2]);
if (m < 3) {
m += 12;
y -= 1;
}
int k = y % 100;
int j = y / 100;
int day = ((d + (((m + 1) * 26) / 10) + k + (k / 4) + (j / 4)) +
(5 * j)) % 7;
System.out.println("That date was " + WEEK_DAYS[day] + ".");
}
}
Comments
Post a Comment