【问题标题】:Determine day of the week by passing specific date? [duplicate]通过传递特定日期来确定星期几? [复制]
【发布时间】:2020-11-17 06:45:19
【问题描述】:

我必须编写一个返回给定日期的日期的方法。因此,如果我通过它(2020 年 11 月 17 日),它应该返回“星期二”。运行程序时,它返回星期四。我在这里做错了什么?

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

【问题讨论】:

    标签: java date calendar


    【解决方案1】:

    tl;博士

    所以,如果我通过它(2020 年 11 月 17 日),它应该返回“TUESDAY”。

    使用java.time

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

    星期二

    详情

    切勿使用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

    星期二

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

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

    看到这个code run live at IdeOne.com

    狂欢

    所有这些都在 Stack Overflow 上多次介绍过。搜索以了解更多信息。

    【讨论】:

      【解决方案2】:

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

      请参阅documentation

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-04-08
          • 2016-06-27
          • 1970-01-01
          • 2017-03-23
          • 1970-01-01
          • 2021-06-29
          • 2017-11-07
          相关资源
          最近更新 更多