查找给定日期的星期几

Nip*_*ara 0 java datetime calendar dayofweek datetime-format

我在hackerrank.com做了一个简单的例子,要求我们返回给定日期的日期.例如:如果日期是08 05 2015(月份日),则应该返回星期三.

这是我为此任务编写的代码

public static String getDay(String day, String month, String year) {
    String[] dates=new String[]{"SUNDAY","MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY","SATURDAY"};
    Calendar cal=Calendar.getInstance();
    cal.set(Integer.valueOf(year),Integer.valueOf(month),Integer.valueOf(day));
    int date_of_week=cal.get(Calendar.DAY_OF_WEEK);
    return dates[date_of_week-1];
}
Run Code Online (Sandbox Code Playgroud)

我的代码返回给定示例的'Saturday',它应该是'Wednesday'.对于2017年10月29日的当前日期,它将返回"星期三".有谁可以帮我解决这个问题?

Ell*_*sch 8

假设您使用的是Java 8+,您可以使用LocalDate类似的东西

public static String getDay(String day, String month, String year) {
    return LocalDate.of(
            Integer.parseInt(year),
            Integer.parseInt(month),
            Integer.parseInt(day)
    ).getDayOfWeek().toString();
}
Run Code Online (Sandbox Code Playgroud)

此外,请注意您所描述的方法服用month,dayyear而是你实现它服用day,monthyear(确保你正确地调用它).我测试了以上内容

public static void main(String[] args) throws Exception {
    System.out.println(getDay("05", "08", "2015"));
    System.out.println(getDay("29", "10", "2017"));
}
Run Code Online (Sandbox Code Playgroud)

我得到了(正如预期的那样)

WEDNESDAY
SUNDAY
Run Code Online (Sandbox Code Playgroud)

如果您不能使用Java 8(或仅修复当前解决方案),请从(is )Calendar获取month偏移量.所以,你需要(和喜欢到,第一返回原始的-第二的实例)像1Calendar#JANUARY0parseIntvalueOfInteger

public static String getDay(String day, String month, String year) {
    String[] dates = new String[] { "SUNDAY", "MONDAY", "TUESDAY", //
            "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY" };
    Calendar cal = Calendar.getInstance();
    cal.set(Integer.parseInt(year), //
            Integer.parseInt(month) - 1, // <-- add -1
            Integer.parseInt(day));
    int date_of_week = cal.get(Calendar.DAY_OF_WEEK);
    return dates[date_of_week - 1];
}
Run Code Online (Sandbox Code Playgroud)

它给出了与上面相同的结果.