Magic dates

The problem

The date June 10th 1960 is special because when we write it in the following format, the month times the day equals the year:

  • 6/10/60

Write a program that asks the user to enter a month (in numeric form), a day, and a two-digit year. The program should then determine whether the day times the month is equal to the year; if so, it should display a message indicating that the date is magic. Otherwise, it should display a message indicating that the date is not magic.

Breaking it down

public static void main(String[] args) {

    // Create a Scanner object for keyboard input.
    Scanner keyboard = new Scanner(;

    // Ask user for input
    System.out.print("Enter date in mm/dd/yyyy format:");
    String dateAsString =;

    // close stream

    // Parse string to date
    LocalDate date = LocalDate.parse(dateAsString,

    // check date and display output
    if (magicDate(date)) {
        System.out.println("That date is magic!");
    } else {
        System.out.println("Sorry, nothing magic about that date...");

 * Method will check if a date is magic define by month * date = last two
 * digets of year
 * @param date
 * @return true if the date is magic
public static boolean magicDate(LocalDate date) {

    int month = date.getMonth().getValue();
    int day = date.getDayOfMonth();
    int year = date.getYear();
    String yearAsString = String.valueOf(year);
    String lastTwoDigits = "0";
    if (yearAsString.length() == 4) {
        lastTwoDigits = yearAsString.substring(2);

    return (month * day) == Integer.parseInt(lastTwoDigits);


Enter date in mm/dd/yyyy format:06/10/1960
That date is magic!

Unit tests

public void test_magic_date() {

    boolean magicDate = MagicDates.magicDate(LocalDate.of(1960, Month.JUNE,


public void test_magic_not_date() {
    boolean magicDate = MagicDates.magicDate(LocalDate.of(1961, Month.JUNE,


Level Up

  • Modify the unit to have mutliple dates using junit parameterized test
  • Validate the date to be in correct MM/dd/yyyy format