日期的很好算,主要是周几比较麻烦。但是只要你知道可以用现在的总天数(现在到1年1月1日)对7取余,就很简单了。
还有就是记得考虑闰年,闰年的公式是整除4不整除100或者整除400.下面是详细代码:
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
if (str == null || str.length() == 0) {
System.out.println("输入不合法!");
}
assert str != null;
String[] strings = str.split("-");
int year = Integer.parseInt(strings[0]);
int month = Integer.parseInt(strings[1].replace("0", ""));
int[] arr = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int day = Integer.parseInt(strings[2].replace("0", ""));
for (int i = 0; i < month - 1; i++) {
day = day + arr[i];
}
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
if (month >= 3) {
day = day + 1;
}
}
System.out.println(day+"天,星期"+weekday(year,day));
}
public static String weekday(int year,int day){
long amount=0;
for(int i=1;i<year;i++){
if((i % 4 == 0 && i % 100 != 0) || i % 400 == 0)
amount++;
}
amount+= 365L *(year-1);
amount+=day;
int week=(int) (amount%7);
String w="";
switch(week){
case 0:w="日";break;
case 1:w="一";break;
case 2:w="二";break;
case 3:w="三";break;
case 4:w="四";break;
case 5:w="五";break;
case 6:w="六";break;
}
return w;
}
}
我这块是面试的时候随手写在main方法里面了,可以自己抽取成单独的方法去使用。项目中还是建议直接使用Data和Calendar类去操作。