0

I have to write a method that returns the day for a given date. So, if I pass it (17/11/2020) it should return "TUESDAY". When running the program it is returning THURSDAY. What am I doing wrong here?

public static String findDay(int month, int day, int year) {
    Calendar calendar = new GregorianCalendar(year, month, day);
    return calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.US).toUpperCase();
}
A-run
  • 470
  • 4
  • 13

3 Answers3

4

tl;dr

So, if I pass it (17/11/2020) it should return "TUESDAY".

Use java.time.

java.time.LocalDate
.of( 2020 , 11 , 17 )
.getDayOfWeek()
.toString()

TUESDAY

Details

Never use Calendar, GregorianCalendar, and so on. Their crazy month numbering where November = 10 is but one of many reasons to avoid these legacy classes.

Use modern java.time classes instead of terrible legacy date-time classes.

String input = "17/11/2020" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;
LocalDate localDate = LocalDate.parse( input , f ) ;
DayOfWeek dow = localDate.getDayOfWeek() ;
System.out.println( dow.toString() ) ;

See this code run live at IdeOne.com.

TUESDAY

In real work, use DayOfWeek::getDisplayName to get text of the localized name of the day of week.

java.time.LocalDate
.of( 2020 , 11 , 17 )
.getDayOfWeek()
.getDisplayName(
    TextStyle.FULL_STANDALONE , 
    Locale.CANADA_FRENCH
)

See this code run live at IdeOne.com.

mardi

All this has been covered many many times on Stack Overflow. Search to learn more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
1

The month value starts at '0'. So '10' will be for 'November'. So when the value '11' is passed in your code, it gives the day for the month of December.

See the documentation.

plaiddroid
  • 30
  • 1
  • 7
1

by using java.time.LocalDate you can pass your 3 paramter and find the dayOfWeek:

public static String findDay(int month, int day, int year) {
    return LocalDate.of(year, month, day).getDayOfWeek().toString();
}
Mustafa Poya
  • 2,615
  • 5
  • 22
  • 36