7

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());
    }
}
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Said
  • 187
  • 1
  • 2
  • 11
  • 4
    `LocalDate.of( 2017 , 8 , 14 ).getDayOfWeek().toString()` —> MONDAY – Basil Bourque Feb 16 '18 at 07:44
  • 4
    Unless you need it to work on legacy code, you are probably wasting your time learning obsolete APIs... – assylias Feb 16 '18 at 07:57
  • @BasilBourque this is Java 8, right? – Said Feb 16 '18 at 11:11
  • @assylias 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 :) – Said Feb 16 '18 at 11:13
  • 3
    @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. – Basil Bourque Feb 16 '18 at 17:55

8 Answers8

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));
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • 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). – Said Feb 16 '18 at 06:05
  • 2
    One: [`Calendar.DAY_OF_WEEK`](https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#DAY_OF_WEEK) is a `static final` constant [`7`](https://docs.oracle.com/javase/8/docs/api/constant-values.html#java.util.Calendar.DAY_OF_WEEK). It does not "become *the actual day of the week*", it never changes. It's a constant. Two: Look at [`Calendar.SUNDAY`](https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#SUNDAY) it's a [`1`](https://docs.oracle.com/javase/8/docs/api/constant-values.html#java.util.Calendar.SUNDAY). Three: Prefer classes in `java.time` over `java.util.Calendar` – Elliott Frisch Feb 16 '18 at 06:19
  • 1
    Alternatively, instead of calling `.format` you can call `.getDayOfWeek().getDisplayName` to automatically localize the name of the day-of-week. – Basil Bourque Feb 16 '18 at 18:22
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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Ravi Solanki
  • 189
  • 3
  • 8
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();

    }
  • 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). – Ole V.V. Jun 16 '20 at 23:56
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);
  }
}
Isurie
  • 310
  • 4
  • 9
  • 1
    FYI, the terribly troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Oct 06 '18 at 20:51
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.

  • 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. – Ole V.V. Sep 29 '19 at 11:10
  • 1
    Ya , you can also do that – PawanSinghla Sep 30 '19 at 12:50
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.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
garima garg
  • 308
  • 1
  • 8
  • 3
    While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) 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. – rizerphe May 12 '20 at 18:28
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();
}
parub
  • 129
  • 1
  • 5
  • 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](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Dec 25 '20 at 19:42
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";            
   
}

}

Akash AR
  • 39
  • 6
  • 2
    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. – Ole V.V. Jul 30 '23 at 18:50