problem: Java Date and Time

chanyayun

fiona

Posted on February 27, 2022

problem: Java Date and Time

Link to the problem

Input would be month day year, and output the day of week.

//sample input
08 05 2015

//sample output
WEDNESDAY
Enter fullscreen mode Exit fullscreen mode

proper solution

DISCLAIMER: the solution referenced from the editorial

public static String findDay(int year, int month, int day) {
    Calendar date = Calendar.getInstance();
    date.set(year, month, day);
    return date.get(Calendar.DAY_OF_WEEK); //error
}
Enter fullscreen mode Exit fullscreen mode

The code would have error because date.get(Calendar.DAY_OF_WEEK) returns integer value of day of week. For example, returns 1 for SUNDAY, 2 for MONDAY, and 7 for SATURDAY.

We need to create an additional array to reference day of week:

// outside main method
static String[] dayOfWeek = {"SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY"};

public static String findDay(int year, int month, int day) {
    Calendar date = Calendar.getInstance();
    date.set(year, month, day);
    return dayOfWeek[date.get(Calendar.DAY_OF_WEEK)-1];
}
Enter fullscreen mode Exit fullscreen mode

use another class

Instead of the class java.util.Calendar it mentioned, java.time.LocalDate (Java 8 and higher) actually finish all the work nice and neat.

public static String findDay(int year, int month, int day) {
    LocalDate date = LocalDate.of(year, month, day);
    return date.getDayOfWeek().toString(); //getDayOfWeek() returns a DayOfWeek object
}
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
chanyayun
fiona

Posted on February 27, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related