gpt4 book ai didi

java - 每季度的天数?

转载 作者:行者123 更新时间:2023-11-30 08:38:38 25 4
gpt4 key购买 nike

我将如何实现 dayNumber_of_quarter

例如3 月 3 日(Q1)应返回 62 = 31(1 月)+ 28(2 月)+ 3(3 月),4 月 29 日(Q2)应返回 29。

到目前为止我的代码:

int month = getMonth(date);
int quarter = getQuarter(date);
int date1 = getDate(date);
int year = getYear(date);
int monthMod = month % 3;
if (monthMod == 0) monthMod = 3;
//System.out.println(monthMod);
int countNumDaysOfQuarter = 0;

if (monthMod == 1) countNumDaysOfQuarter = getDate(date);
if (monthMod == 2) countNumDaysOfQuarter = getDate(date) + getCountOfDaysInMonth(date1, month - 1, year);
if (monthMod == 3) countNumDaysOfQuarter = getDate(date) + getCountOfDaysInMonth(date1, month - 1, year) + getCountOfDaysInMonth(date1, month - 2, year);

最佳答案

这是一个使用 Java 8 的简单实现:

public static long dayOfQtr(LocalDate date) {
LocalDate firstDayOfQtr = LocalDate.of(date.getYear(), (qtr(date) - 1) * 3 + 1, 1);
return ChronoUnit.DAYS.between(firstDayOfQtr, date) + 1;
}
public static int qtr(LocalDate date) {
return (date.getMonthValue() - 1) / 3 + 1;
}

测试

for (int i = 1; i <= 12; i++) {
LocalDate date = LocalDate.of(2016, i, i);
System.out.println(date + " is day " + dayOfQtr(date) + " of Q" + qtr(date));
}

输出

2016-01-01 is day 1 of Q1
2016-02-02 is day 33 of Q1
2016-03-03 is day 63 of Q1
2016-04-04 is day 4 of Q2
2016-05-05 is day 35 of Q2
2016-06-06 is day 67 of Q2
2016-07-07 is day 7 of Q3
2016-08-08 is day 39 of Q3
2016-09-09 is day 71 of Q3
2016-10-10 is day 10 of Q4
2016-11-11 is day 42 of Q4
2016-12-12 is day 73 of Q4

关于java - 每季度的天数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36468769/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com