1185. 一周中的第几天

题目

给你一个日期,请你设计一个算法来判断它是对应一周中的哪一天。

输入为三个整数:daymonthyear,分别表示日、月、年。

您返回的结果必须是这几个值中的一个 {“Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”}。

示例1:

1
2
输入:day = 31, month = 8, year = 2019
输出:"Saturday"

示例2:

1
2
输入:day = 18, month = 7, year = 1999
输出:"Sunday"

示例3:

1
2
输入:day = 15, month = 8, year = 1993
输出:"Sunday"

提示:

  • 给出的日期一定是在 19712100 年之间的有效日期。

解法

解法一:

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
private String[] days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
public String dayOfTheWeek(int day, int month, int year) {
String format = year + "-" + month + "-" + day;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date d;
try {
d = sdf.parse(format);
} catch (ParseException e) {
return days[0];
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);

return days[calendar.get(Calendar.DAY_OF_WEEK) - 1];
}
0%