通过传递特定日期来确定星期几?

Determine day of the week by passing specific date?

我必须编写一个方法来 return 指定日期的日期。因此,如果我通过它 (17/11/2020),它应该 return“星期二”。当 运行 节目是 return 星期四。我在这里做错了什么?

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();
}

tl;博士

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

使用java.time.

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

TUESDAY

详情

切勿使用 CalendarGregorianCalendar 等。他们疯狂的月份编号,其中 11 月 = 10 只是避免这些遗留问题的众多原因之一 类。

使用现代 java.time 类 而不是糟糕的遗留日期时间 类.

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() ) ;

看到这个 code run live at IdeOne.com

TUESDAY

在实际工作中,使用DayOfWeek::getDisplayName获取星期几的本地化名称文本。

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

看到这个 code run live at IdeOne.com

mardi

所有这些都已在 Stack Overflow 上多次提及。搜索以了解更多信息。

月份值从“0”开始。所以“10”将代表 'November'。因此,当在您的代码中传递值“11”时,它给出了 12 月的日期。

查看documentation

通过使用 java.time.LocalDate 你可以传递你的 3 参数并找到 dayOfWeek:

public static String findDay(int month, int day, int year) {
    return LocalDate.of(year, month, day).getDayOfWeek().toString();
}