Search code examples
javadatedayofweekjava.util.calendar

getDay() method to return day of the week for a given date not works


I'm trying to complete the task named Java Date and Time on HackerRank.

Task

You are given a date. You just need to write the method, getDay, which returns the day on that date.For example, if you are given the date, August 14th 2017, the method should return MONDAY as the day on that date.

I tried my best to do the task but I get either the null result or NullPointerException error. I wonder where do I do wrong. Below is my code:

Thanks in advance!

My Code:

import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String month = in.next();
        String day = in.next();
        String year = in.next();

        System.out.println(getDay(day, month, year));
    }

    public static String getDay(String day, String month, String year) {
        Calendar cal = Calendar.getInstance();
        cal.set(Integer.valueOf(year), (Integer.valueOf(month) - 1), Integer.valueOf(day));
        return cal.getDisplayName(cal.get(Calendar.DAY_OF_WEEK), Calendar.LONG, Locale.getDefault());
    }
}

Solution

  • Your return is off; you don't want cal.get in the first column of cal.getDisplayName. Currently, I get the month name with your code. Change that to

    return cal.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.getDefault());
    

    And call it like

    public static void main(String[] args) {
        System.out.println(getDay("14", "8", "2017"));
    }
    

    And I get (as expected)

    Monday
    

    In new code, I would prefer the new classes in java.time (Java 8+), and a DateTimeFormatter - like,

    public static String getDay(String day, String month, String year) {
        int y = Integer.parseInt(year), m = Integer.parseInt(month), d = Integer.parseInt(day);
        return java.time.format.DateTimeFormatter.ofPattern("EEEE")
                .format(LocalDate.of(y, m, d));
    }