gpt4 book ai didi

java - 查找给定日期是星期几

转载 作者:行者123 更新时间:2023-12-01 06:42:30 25 4
gpt4 key购买 nike

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

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

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];
}

对于给定的示例,我的代码返回“星期六”,该示例应该是“星期三”。对于当前日期 2017 年 10 月 29 日,它返回“星期三”。谁能帮我解决这个问题吗?

最佳答案

假设您使用的是 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();
}

另请注意,您将该方法描述为采用,但您实现该方法仅采用 code>、monthyear (确保您正确调用它)。我测试了上面的内容

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

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

WEDNESDAY
SUNDAY

如果您无法使用 Java 8(或只是为了修复当前的解决方案),Calendar1 偏移量(Calendar#JANUARY0)。因此,您需要(并且更喜欢 parseInt 而不是 valueOf,第一个返回一个基元 - 第二个返回 Integer 实例)类似

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];
}

得到与上面相同的结果。

关于java - 查找给定日期是星期几,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46998000/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com