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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

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

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay