DEV Community

fiona
fiona

Posted on • Edited on

3 2

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More