【发布时间】:2017-09-07 16:53:54
【问题描述】:
我正在尝试根据特定规则计算周数。我正在寻找的规则示例是:
第 1 周 = 一年中的第一周,其中包含 4 月 1 日。
示例数据:
2017 年 3 月 27 日第 1 周 2017 年 4 月 2 日
...
2017 年 9 月 4 日第 23 周 2017 年 9 月 10 日
我发现了一个类似的问题 - Getting Week number of year starting from April - 并以此为指导,我想出了以下内容,该问题适用于未来的特定日期。但是,截止日期之前的日期时间,但在当前一周,会导致问题。
LocalDate firstOne = LocalDate.FromDateTime(dateTime);
int targetYear = firstOne.Month > 4 || firstOne.Month == 4 && firstOne.Day >= 1 ? firstOne.Year : firstOne.Year - 1;
LocalDate start = new LocalDate(targetYear, 4, 1);
int days = Period.Between(start, firstOne, PeriodUnits.Days).Days;
int targetWeek = (days / 7) + 1;
if (targetWeek >= 52)
{
// if we are greater than 52 then we are technically in week 1 of the following year; eg 31st March 2017.
// Remove the "year" from the week count and move the year counter back to the correct year.
targetWeek -= 52;
targetYear++;
}
return (targetYear, targetWeek);
当前的问题是,如果我在 2017 年 3 月 27 日(即 1 日的 7 天内)通过,它仍然给出前一年和第 52 周。我猜我需要以某种方式考虑周开始天(? !)。
【问题讨论】:
-
只是检查一下,您认为什么是“周” - 周一到周日,还是其他?
-
@JonSkeet 我认为最初是周一到周日,但我认为我可能还必须使其可配置以满足未来的不同需求。
-
好的。将在我的答案中指出在哪里设置。
-
@JonSkeet 完美,谢谢!
-
在计算
targetYear(第二行)时,不应该在firstOne上加上7 天,看看4 月1 日是否在范围内?