我正在尝试制作一个日历,但是我面临一个问题,从周日开始的月份被切断了他们的第一周。其他一切似乎都可以工作,比如一个月的天数,日期实际上是正确的:
August 2021
MON TUE WED THU FRI SAT SUN
02 03 04 05 06 07 08
09 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
这是我到目前为止的代码:
DateTime displayMonth = new DateTime(2021, 8, 1); // This will be dynamic, ofc.
int firstDay = (int)displayMonth.DayOfWeek;
int cellCounter = 0;
int daysInMonth = (int)DateTime.DaysInMonth(displayMonth.Year, displayMonth.Month);
int weeksInMonth = (int)Math.Ceiling((double)(firstDay + daysInMonth) / 7);
for (var w = 0; w <= weeksInMonth; w++)
{
<div class="row">
@for (var d = 0; d < 7; d++)
{
cellCounter++;
<div class="col">
@{
int day = 1 + cellCounter - firstDay;
if (day > 0 && day <= daysInMonth)
{
<h1>@day</h1>
}
}
</div>
}
</div>
}
我已经知道DayOfWeek
和Sunday的指标值为0。我所没有的,是一个"转变"。将星期一改为0:
int firstDay = ((int)displayMonth.DayOfWeek + 6) % 7;
工作代码:
DateTime displayMonth = new DateTime(2021, 9, 1);
int firstDay = ((int)displayMonth.DayOfWeek + 6) % 7;
int cellCounter = 0;
int daysInMonth = (int)DateTime.DaysInMonth(displayMonth.Year, displayMonth.Month);
int weeksInMonth = (int)Math.Ceiling((double)(firstDay + daysInMonth) / 7);
for (var w = 0; w <= weeksInMonth; w++)
{
<div class="row">
@for (var d = 0; d < 7; d++)
{
cellCounter++;
<div class="col">
@{
int day = cellCounter - firstDay;
if (day > 0 && day <= daysInMonth)
{
<h1>@day</h1>
}
}
</div>
}
</div>
}