从这个字符串中截取出生年份2018,月份7,天数15最后打印输出2018年7月15日有181天,用java
时间: 2024-06-01 11:11:15 浏览: 50
String str = "2018-07-15";
String[] arr = str.split("-");
int year = Integer.parseInt(arr[0]);
int month = Integer.parseInt(arr[1]);
int day = Integer.parseInt(arr[2]);
System.out.println(year + "年" + month + "月" + day + "日有" + (365 - calculateDays(year, month, day)) + "天");
// 计算距离今年结束还有多少天
public static int calculateDays(int year, int month, int day) {
int days = 0;
for (int i = month + 1; i <= 12; i++) {
days += getDaysOfMonth(year, i);
}
days += getDaysOfMonth(year, month) - day + 1;
return days;
}
// 判断一个月有多少天
public static int getDaysOfMonth(int year, int month) {
int days = 0;
switch (month) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
days = 31;
break;
case 4: case 6: case 9: case 11:
days = 30;
break;
case 2:
if (isLeapYear(year)) {
days = 29;
} else {
days = 28;
}
break;
default:
break;
}
return days;
}
// 判断是否为闰年
public static boolean isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
}
阅读全文