用Java编写一个判断指定日期为星期几的代码
时间: 2024-05-03 09:21:20 浏览: 69
将日期换算成星期几的Java代码
4星 · 用户满意度95%
以下是用Java编写的判断指定日期为星期几的代码:
```java
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DayOfWeekFinder {
public static void main(String[] args) {
String dateStr = "2021-12-31"; // 指定日期,格式为yyyy-MM-dd
String dayOfWeek = getDayOfWeek(dateStr);
System.out.println(dateStr + "是星期" + dayOfWeek);
}
public static String getDayOfWeek(String dateStr) {
String dayOfWeek = "";
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse(dateStr);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int day = calendar.get(Calendar.DAY_OF_WEEK);
switch (day) {
case Calendar.SUNDAY:
dayOfWeek = "日";
break;
case Calendar.MONDAY:
dayOfWeek = "一";
break;
case Calendar.TUESDAY:
dayOfWeek = "二";
break;
case Calendar.WEDNESDAY:
dayOfWeek = "三";
break;
case Calendar.THURSDAY:
dayOfWeek = "四";
break;
case Calendar.FRIDAY:
dayOfWeek = "五";
break;
case Calendar.SATURDAY:
dayOfWeek = "六";
break;
}
} catch (Exception e) {
e.printStackTrace();
}
return dayOfWeek;
}
}
```
该代码通过SimpleDateFormat将指定日期字符串转换为Date对象,再通过Calendar获取该日期的星期几,最后根据星期几的值返回相应的字符串。
阅读全文