0

Can you Explain this java-Calendar code

Calendar calendar = Calendar.getInstance();

calendar.set(Calendar.MONTH, month-1);

Why we are passing the value of month decreasing it by one

calendar.set(Calendar.DAY_OF_MONTH, day);

calendar.set(Calendar.YEAR, year);

return calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.US).toUpperCase();

  • 1
    Probably changing from a one-based month (1-12) to a zero-based month (0-11). – Fred Larson Jun 09 '21 at 17:56
  • 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](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Jun 10 '21 at 03:47
  • Instead of those 5 lines of code just do `return LocalDate.of(year, month, day).getDayOfWeek().toString();`. java.time is so much nicer to work with. And there’s no subtracting 1 or any other funny constant. – Ole V.V. Jun 10 '21 at 04:24

1 Answers1

1

Avoid legacy classes

Among the many problems with the terrible old date-time classes bundled with the earliest versions of Java is their whacky numbering. Months of the year are numbered 0-11 for January-December.

Never use these legacy classes, Calendar, Date, etc.

java.time

Use only java.time classes.

Apparently you want the current date.

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
LocalDate today = LocalDate.now( z ) ;

If you want to switch month but keep the year and day-of-month, use withMonth method.

LocalDate ld = today.withMonth( Month.JANUARY ) ;

To quote the Javadoc:

Returns a copy of this LocalDate with the month-of-year altered.

If the day-of-month is invalid for the year, it will be changed to the last valid day of the month.

Since it seems that you want the name of the day of the week in uppercase in English, this is straightforward:

System.out.println( ld.getDayOfWeek() ) ;

SUNDAY

getDayOfWeek returns a DayOfWeek enum constant. If you need a String, use its toString method.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154