代码改变世界

java 判断星期几

2021-11-29 09:36  sunice  阅读(811)  评论(0编辑  收藏  举报
 1 //判断星期几
 2 private String calculateWeekDay(Date weekDate) {
 3     Calendar calendar = Calendar.getInstance();
 4     calendar.setTime(weekDate);
 5 
 6     int year = calendar.get(Calendar.YEAR);
 7     int month = calendar.get(Calendar.MONTH) + 1;
 8     int day = calendar.get(Calendar.DATE);
 9 
10     if (month == 1 || month == 2) {
11         month += 12;
12         year--;
13     }
14     int weekCalculate = (day + 2 * month + 3 * (month + 1) / 5 + year + year / 4 - year / 100 + year / 400 + 1) % 7;
15     String week = "";
16     switch (weekCalculate) {
17         case 1:
18             week = "星期一";
19             break;
20         case 2:
21             week = "星期二";
22             break;
23         case 3:
24             week = "星期三";
25             break;
26         case 4:
27             week = "星期四";
28             break;
29         case 5:
30             week = "星期五";
31             break;
32         case 6:
33             week = "星期六";
34             break;
35         case 0:
36             week = "星期日";
37             break;
38     }
39     return week;
40 }