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

8

8

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());
    }
}
Kenji answered 16/2, 2018 at 5:39 Comment(5)
LocalDate.of( 2017 , 8 , 14 ).getDayOfWeek().toString() —> MONDAYPournaras
Unless you need it to work on legacy code, you are probably wasting your time learning obsolete APIs...Flit
@BasilBourque this is Java 8, right?Kenji
@Flit I've just started to do the challenges on HackerRank. I'm a real newbie in programming but I want to be a good competitive programmer eventually. If you have a better advice, I'll be glad to hear it :)Kenji
@SaidBuyukarslan The java.time classes are built into Java 8 and later. Much of their functionality is back-ported to Java 6 & 7 in the ThreeTen-Backport project. Well-worth adding to your project as the legacy classes are an awful mess. Search Stack Overflow for more info. This has been addressed many times already.Pournaras
C
12

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));
}
Columbuscolumbyne answered 16/2, 2018 at 5:45 Comment(3)
It really worked, thank you! Btw, I have two quick questions: 1. After the line cal.set(Integer.valueOf(year), (Integer.valueOf(month) - 1), Integer.valueOf(day));, the value of Calendar.DAY_OF_WEEK becomes the actual day of the week, not the system's current day, right? and 2. using cal.get(Calendar.DAY_OF_WEEK) for a string call would be best if I just want to have the int value of the day alone. like: int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK); (which returns something between 1-7).Kenji
One: Calendar.DAY_OF_WEEK is a static final constant 7. It does not "become the actual day of the week", it never changes. It's a constant. Two: Look at Calendar.SUNDAY it's a 1. Three: Prefer classes in java.time over java.util.CalendarColumbuscolumbyne
Alternatively, instead of calling .format you can call .getDayOfWeek().getDisplayName to automatically localize the name of the day-of-week.Pournaras
M
3

java.time.LocalDate

The modern approach uses the java.time classes.

  1. Import java.time.* to access LocalDate & DayOfWeek classes.
  2. Write getDay method which should be static because it is called in main method.
  3. Retrieve localDate by using of method which takes 3 arguments in "int" format.
  4. convert the getDay method arguments in int format.
  5. finally retrieve name of that day using getDayOfWeek method.

There is one video on this challenge. Java Date and Time Hackerrank

LocalDate                 // Represent a date-only value, without time-of-day and without time zone.
.of( 2018 , 1 , 23 )      // Pass year-month-day, 1-12 for January-December. 
.getDayOfWeek()           // Obtain a `DayOfWeek` enum object.
.getDisplayName(          // Automatically localize the name of the day-of-week.
    TextStyle.FULL ,      // How long or abbreviated.
    Locale.US             // Or Locale.CANADA_FRENCH or so on.
)                         // Returns `String` such as `Monday` or `lundi`. 

For Java 6 & 7, see the ThreeTen-Backport project. For earlier Android, see the ThreeTenABP project.

Millner answered 30/9, 2018 at 7:10 Comment(0)
O
3

if you want to use LocalDate, you can use it this way

 import java.time.LocalDate;

 public static String getDay(int month, int day, int year) {

    return LocalDate.of(year, month, day).getDayOfWeek().name();

    }
Osteogenesis answered 16/6, 2020 at 14:34 Comment(1)
Thanks for contributing. It’s certainly a good suggestion, I think it’s already in a number of the other answers (with very slight variations).Awed
H
1

Formatting data and time using java.util date and calendar as follows, where it needed to handle an exception with java.text.SimpleDateFormat in java 7.

public static void main(String[] args){
    String inputDateStr = String.format("%s/%s/%s", 23, 04, 1995);
    Date inputDate = null;
    try {
        inputDate = new SimpleDateFormat("dd/MM/yyyy").parse(inputDateStr);
    } catch (ParseException ex) {
        Logger.getLogger(JavaApplication28.class.getName()).log(Level.SEVERE, null, ex);
    }
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(inputDate);
    String dayOfWeek = calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.US).toUpperCase();
    System.out.println(dayOfWeek);

}

Formatting date and time using java.time classes in java 8 as follows and it is immutable and thread-safe.

import java.time.LocalDateTime; 
import java.time.format.DateTimeFormatter; 

public class Main {
  public static void main(String[] args) {
    LocalDateTime dateObj = LocalDateTime.now();
    System.out.println("Before formatting: " + dateObj);
    DateTimeFormatter formatObj = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");

    String formattedDate = dateObj.format(formatObj);
    System.out.println("After formatting: " + formattedDate);
  }
}
Hooligan answered 6/10, 2018 at 10:27 Comment(1)
FYI, the terribly troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 and later. See Tutorial by Oracle.Pournaras
C
1
    public static String getDay(int month, int day, int year) {
   String  res= java.time.format.DateTimeFormatter.ofPattern("EEEE")
        .format(java.time.LocalDate.of(year, month, day));
   return res;    }

must use java.time.LocalDate, if u will use direct LocalDate its show compile time error i.e cannot find symbol, so plz use java.time.

Cyperaceous answered 28/9, 2019 at 17:7 Comment(2)
You may add importstatements import java.time.LocalDate; and import java.time.format.DateTimeFormatter;, then you don’t need the qualifications java.time and java.time.format in the method.Awed
Ya , you can also do thatCyperaceous
L
1

You can use new Java8 DateTime API.

public static String getDay(int day, int month, int year) 
{
    LocalDate dt=LocalDate.of(year, month, day);
    System.out.println("day: " + dt.getDayOfWeek().toString());
    return dt.getDayOfWeek().toString();
}

A LocalDate is a date without time of day, so fine for our purpose. The of factory method constructs the date that we want. Contrary to the Calendar class used in the question it numbers the months sanely from 1 for January through 12 for December. A LocalDate has a getter for day of week. It returns a constant from the DayOfWeek enum whose toString method gives us a nice readable string such as MONDAY, again in contrast to what we get from Calendar.

Latium answered 12/5, 2020 at 17:41 Comment(1)
While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.Soledadsolely
V
1
public static String findDay(int month, int day, int year) {
 Calendar cal = Calendar.getInstance();
    cal.set(year, (month - 1), day);
    String dayOfWeek = cal.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.getDefault());
    return dayOfWeek.toUpperCase();
}
Vehemence answered 25/12, 2020 at 4:13 Comment(1)
I recommend you don’t use Calendar. That class is poorly designed and long outdated. Instead use LocalDate and DayOfWeek, both from java.time, the modern Java date and time API.Awed
D
0
public static String findDay(int month, int day, int year) {
     Calendar rightNow = Calendar.getInstance();
        rightNow.set(year, month-1, day);;
        switch(rightNow.get(Calendar.DAY_OF_WEEK)) {
            case Calendar.SUNDAY:
                return "SUNDAY";
            case Calendar.MONDAY:
                return "MONDAY";
            case Calendar.TUESDAY:
                return "TUEDAY";
            case Calendar.WEDNESDAY:
                return "WEDNESDAY";
            case Calendar.THURSDAY:
                return "THURSDAY";
            case Calendar.FRIDAY:
                return "FRIDAY";
            case Calendar.SATURDAY:
                return "SATURDAY";            
   
}

}

Displacement answered 30/7, 2023 at 15:43 Comment(1)
Thanks for wanting to contribute. This is a poor answer in some respects. As many have pointed out already, no one should use the cumbersome and outdated Calendar class anymore. The code is too manual, too handheld. Compare to the simpler and shorter code in each and every other answer. And code-only answers are not very useful. It’s from the explanations that we all learn. So in your next answers, please provide some.Awed

© 2022 - 2025 — McMap. All rights reserved.