3 回答
TA贡献1784条经验 获得超2个赞
看起来您想要的想法是一种按月递减的递归方法。
static int dayNumberInYear(int day, Month month, int year)
{
if(!month.equals(Month.JANUARY)) {
return day + dayNumberInYear(numberOfDaysInMonth(month.minus(1), year), month.minus(1), year);
} else {
return day;
}
}
请注意,在这种递归方法中,基本情况是现在是一月,我们只需返回一月的当天。否则,我们将添加当前月份的某一天,然后添加之前每个月的所有天数。
它也可以作为 for 循环来完成。
static int dayNumberInYearByLoop(int day, Month month, int year) {
int totalDays = day;
for (int i = month.getValue();i>1;i--) {
totalDays += numberOfDaysInMonth(Month.of(i), year);
}
return totalDays;
}
TA贡献1911条经验 获得超7个赞
package SO;
import java.time.Month;
public class test {
//below array contain number of total days in that month(non leap year).
static int arrTotal[] = { 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
public static void main(String[] args) {
System.out.println(dayNumberInYear(3, Month.MARCH, 2019));
}
static int dayNumberInYear(int day, Month month, int year) {
int dayNumberInYear = day + numberOfDaysInMonth(year, month);
return dayNumberInYear;
}
private static int numberOfDaysInMonth(int year, Month month) {
int add = 0;
if (year % 4 == 0)
add++;
int a = month.getValue();
return arrTotal[(a - 2)] + add;
}
}
TA贡献2051条经验 获得超10个赞
就这么简单。
public static String dayNumberInYear(String sDate) {
//sDate formate 2023-02-20, you can change local date format
LocalDate localDate = LocalDate.parse(sDate);
int dayOfYear = localDate.getDayOfYear();
return dayOfYear > 99 ? "" + dayOfYear : dayOfYear > 9 ? "0" + dayOfYear : "00" + dayOfYear;
}
添加回答
举报