Shibaku Shibaku - 2 months ago 6
Java Question

How to split a date into usable doubles

I have this code that is meant to find the day of the week of a specific date. (Example: 09/21/2016 = Wednesday).

Currently the user enters the month, day, and year one by one. However, I want to change it so that the user may enter it in the format MM/DD/YYYY.

I'm having trouble splitting the month, day, and year from the format MM/DD/YYYY.

Scanner keyboard = new Scanner(System.in);
double MM;
double DD;
double YYYY;
double pOne;
double pTwo;
double pThree;
int pFour;

System.out.print("Enter the month (MM): ");
MM = keyboard.nextInt();

System.out.print("Enter the day (DD): ");
DD = keyboard.nextInt();

System.out.print("Enter the year (YYYY): ");
YYYY = keyboard.nextInt();

pOne = (YYYY - ((14 - MM) / 12));
pTwo = (pOne + ((pOne / 4) - (pOne / 100) + (pOne / 400)));
pThree = ((MM + 12) * ((14 - MM) / 12) - 2);
pFour = (int) ((DD + pTwo + ((31 * pThree) / 12)) % 7);

Answer

Prompt the user to enter date in the format you want, i.e. MM/DD/YYYY. Then use split() like so:

String date = keyboard.nextLine();
String[] parts = date.split("/");
double MM = Double.valueOf(parts[0]);
double DD = Double.valueOf(parts[1]);
double YYYY = Double.valueOf(parts[2]);

Then use the double variables in your calculation.

Read this SO post to learn about the differences between Double.parseDouble() and Double.valueOf().

Comments