Java 计算日期是该年的第几天
public static int getDayOfYear(int year, int month, int day) {
int[] daysInMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) {
daysInMonth[1] = 29; // 闰年
}
int dayOfYear = 0;
for (int i = 0; i < month - 1; i++) {
dayOfYear += daysInMonth[i];
}
dayOfYear += day;
return dayOfYear;
}
该函数先根据年份判断二月份的天数(闰年29天,平年28天),然后遍历月份,累加天数,最后加上日数即可。
原文地址: https://www.cveoy.top/t/topic/oacP 著作权归作者所有。请勿转载和采集!