[Java] Calculate the day of the week from the date (Calendar class is not used)

Introduction

The other day, I'm reading a book called "Mental Calculation Master" that I found at a second-hand bookstore. There was a ** method to calculate the day of the week from the date **, so when I tried it using my birthday, it matched perfectly.

** Enjoy math! ** **

so,

I tried to put it in the program. I usually use the Calendar class, so it's refreshing to calculate the day of the week by myself.

** Enjoy programming! ** **

processing

package math;

import java.util.HashMap;
import java.util.Map;

/**
 *Calculation of day of the week from date
 * -1900s and 2000s can be calculated
 * -Leap years are not considered
 */
public class CalcDayOfWeek {

	/**Code for the month(key:Month/val:Code) */
	private static final Map<Integer, Integer> SIGN_OF_MONTH = new HashMap<>();
	static {
		SIGN_OF_MONTH.put( 1, 6);
		SIGN_OF_MONTH.put( 2, 2);
		SIGN_OF_MONTH.put( 3, 2);
		SIGN_OF_MONTH.put( 4, 5);
		SIGN_OF_MONTH.put( 5, 0);
		SIGN_OF_MONTH.put( 6, 3);
		SIGN_OF_MONTH.put( 7, 5);
		SIGN_OF_MONTH.put( 8, 1);
		SIGN_OF_MONTH.put( 9, 4);
		SIGN_OF_MONTH.put(10, 6);
		SIGN_OF_MONTH.put(11, 2);
		SIGN_OF_MONTH.put(12, 4);
	}

	/**Code for the day of the week(key:Code/val:Calculation results) */
	private static final Map<Integer, String> SIGN_OF_WEEK  = new HashMap<>();
	static {
		SIGN_OF_WEEK.put(1, "Mon.");
		SIGN_OF_WEEK.put(2, "Tue.");
		SIGN_OF_WEEK.put(3, "Wed.");
		SIGN_OF_WEEK.put(4, "Thu.");
		SIGN_OF_WEEK.put(5, "Fri.");
		SIGN_OF_WEEK.put(6, "Sat.");
		SIGN_OF_WEEK.put(0, "Sun.");
	}

	/**Year(First 2 digits)Specific gravity for*/
	private static final Map<Integer, Integer> WEIGHT_OF_YEAR = new HashMap<>();
	static {
		WEIGHT_OF_YEAR.put(19, 1);
		WEIGHT_OF_YEAR.put(20, 0);
	}

	/**
	 *Main({@link #calcDayOfWeek}Just call)
	 * @param args
	 */
	public static void main(String[] args) {
		calcDayOfWeek("1993/09/17"); //For the time being, my birthday
		calcDayOfWeek("2017/09/17"); //This year's birthday

		calcDayOfWeek("2001/09/11"); //Terrorist attacks in the United States
		calcDayOfWeek("2011/03/11"); //Great East Japan Earthquake
		calcDayOfWeek("1989/11/09"); //Berlin wall collapse
	}

	/**
	 *Day of the week calculation
	 * -Year: 25 last 2 digits%Add the value and the last two digits.(However, the specific gravity is added depending on the age.)
	 * -Month: Obtained from sign mapping to month
	 * -Date: Use as is
	 * @param yyyyMMdd
	 */
	public static void calcDayOfWeek(String yyyyMMdd) {
		if (yyyyMMdd == null)
			return;
		yyyyMMdd = yyyyMMdd.replaceAll("-", "").replaceAll("/", "").replaceAll(" ", "");
		if (!checkFormat(yyyyMMdd))
			return;

		int yy     = Integer.parseInt(yyyyMMdd.substring(2, 4));
		int mm     = Integer.parseInt(yyyyMMdd.substring(4, 6));
		int dd     = Integer.parseInt(yyyyMMdd.substring(6, 8));
		int weight = WEIGHT_OF_YEAR.get(Integer.parseInt(yyyyMMdd.substring(0, 2)));

		int signOfYear  = (yy / 4) + yy + weight;
		int signOfMonth = SIGN_OF_MONTH.get(mm); 
		int signOfDay   = dd;

		System.out.println(String.format("%s is %s",yyyyMMdd, SIGN_OF_WEEK.get((signOfYear + signOfMonth + signOfDay) % 7)));
	}

	private static boolean checkFormat(String yyyyMMdd) {
		try {
			Integer.parseInt(yyyyMMdd);
			return yyyyMMdd.length() == 8;
		} catch (NumberFormatException e) {
			return false;
		}
	}
}

Output result

For the time being, my birthday and global news ...

19930917 is Fri.
20170917 is Sun.
20010911 is Tue.
20110311 is Fri.
19891109 is Thu.

Impressions

・ The calculation itself is not troublesome, but it is difficult to remember the sign mapping (SIGN_OF_MONTH) for the month. ・ The process will be a little more complicated considering the leap year, but it doesn't seem to be that big (* I may update it as soon as I check it). ・ I don't know about the 1800s and 2100s (* I may update it as soon as I check it)

If you can calculate it in your head, you can use it at a joint party and it seems to be popular. (suitable)

Recommended Posts

[Java] Calculate the day of the week from the date (Calendar class is not used)
Output of the day of the week using Ruby's Date class
[Ruby] Display today's day of the week using Date class
[Java1.8 +] Get the date of the next x day of the week with LocalDate
[Java] Get the day of the specific day of the week
From Java9, the constructor of the class corresponding to primitive types is deprecated.
Display Japanese calendar and days of the week using java8 standard class
[Ubuntu 20.04] Display the day of the week on the date / clock
[Java] I want to calculate the difference from the date
[Java] Get the date 10 days later with the Calendar class
Java unit test Judgment of specified day of the week Determines whether ArDate, Date, Calendar, and long are specified days of the week.
Java is the 5th day
Was done in the base year of the Java calendar week
What is the LocalDateTime class? [Java beginner] -Date and time class-
Java Calendar is not a singleton.
Why Java Vector is not used
Change the conversation depending on which day of the week is today
[Java beginner] Conversion from character string to numerical value-What is the parseInt method of the Integer class? ~
[Java Servlet] The road of Senri is also the fifth step from the first step
[Java Servlet] The road of Senri is also the third step from the first step
[day: 5] I summarized the basics of Java
Error when the member of Entity class used in SpringWebFlux is final
[Java] How to use the Calendar class
[Java Servlet] The road of Senri is also the fourth step from the first step
[Java] Get the date with the LocalDateTime class
Java / Kotlin: Calculate the quotient by specifying the number of significant digits when it is not divisible by the division (division) of BigDecimal.
Increment with the third argument of iterate method of Stream class added from Java9
[Java] Where is the implementation class of annotation that exists in Bean Validation?
Retrieve the first day of week in current locale (what day of the week is it today?)
Cause of is not visible when calling a method of another class in java
Zeller's official (asking for the day of the week)
I want to output the day of the week
ActiveSupport underscore is not the inverse of camelize
The order of Java method modifiers is fixed
How to get today's day of the week
Calculate the similarity score of strings with JAVA
[Ruby] Code to display the day of the week
The date time of java8 has been updated
First touch of the Files class (or Java 8)
[Java] How to use Calendar class and Date class
[Java] How to display the day of the week acquired by LocalDate, DateTimeformatter in Japanese
Getting a little stuck on the last day of the month using Java's Calendar class
[Java] How to use compareTo method of Date class
In Time.strptime,% j (total date of the year) is
How to write Scala from the perspective of Java
The comparison of enums is ==, and equals is good [Java]
When the month of the date is acquired, the January shift
Why the get method is needed in the Calendar class
Summarize the additional elements of the Optional class in Java 9
Use of Date class
Judgment of the calendar
Find the address class and address type from the IP address with Java
Get the next business day after the specified date in JAVA
Get to the abbreviations from 5 examples of iterating Java lists
When using the constructor of Java's Date class, the date advances by 1900.
How to create a form to select a date from the calendar
[Java] com.sun.glass.WindowEvent is imported and the window does not close
[Rails] When the layout change of devise is not reflected
Java: The problem of which is faster, stream or loop
How to derive the last day of the month in Java
[Java] Delete the specified number of characters from the end of StringBuilder