[英]Calendar Can't Show Previous Months Days In First Week
I'm learning C# and I wanted to make a calendar to learn DateTime.我正在学习 C#,我想制作一个日历来学习 DateTime。 I did make a calendar but now I want to see previous months days in first week like in this photo .
我确实做了一个日历,但现在我想在第一周看到前几个月的日子,就像这张照片一样。 I tried few things but I really don't remember all.
我尝试了几件事,但我真的不记得全部了。 Here is my code and if there any way to improve it just say.
这是我的代码,如果有任何改进方法,请说。 I'm using WinForms for ui.
我正在为 ui 使用 WinForms。
DateTime now = DateTime.Now;
Month = now.Month;
Year = now.Year;
// count of days of the month
int days = DateTime.DaysInMonth(Year, Month);
// first day of the month
DateTime startofthemonth = new DateTime(Year, Month,1);
// last day of the month
var endofthemonth = startofthemonth.AddDays(-1);
// convert the startofthemonth to int
int dayoftheweek = Convert.ToInt32(startofthemonth.DayOfWeek.ToString("d")) + 6;
// convert the endofthemonth to int
int lastdayinmonth = Convert.ToInt32(endofthemonth.DayOfWeek.ToString("d"));
// blank user control
for (int i = lastdayinmonth; i <= lastdayinmonth; i--)
{
UCBlankDay uCBlankDay = new UCBlankDay();
uCBlankDay.BlankDays(i);
flowLayoutPanel1.Controls.Add(uCBlankDay);
}
// day user control
for (int i = 1; i <= days; i++)
{
UCDay uCDay = new UCDay();
uCDay.Days(i);
flowLayoutPanel1.Controls.Add(uCDay);
}
}
to be clear code works without showing previous months days in first week清晰的代码可以在第一周不显示前几个月的日子
I've recently done a calendar and I found that when you are in the month view, it's better to divide your month in weeks first instead of days right away.我最近做了一个日历,我发现当您在月视图中时,最好先将您的月划分为周而不是立即划分天。
I would use your 1st day of the month and find the first day of the week doing something like this:我会使用您每月的第一天并找到一周的第一天做这样的事情:
public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
{
int diff = (7 + (dt.DayOfWeek - startOfWeek)) % 7;
return dt.AddDays(-1 * diff).Date;
}
startofthemonth = date.StartOfMonth().StartOfWeek(startDay);
I would then iterate by weeks instead of days like this然后我会迭代几周而不是像这样的几天
do
{
Weeks.Add(new UCBlankWeek(**Your day logic will be inside this constructor**));
startofthemonth = startofthemonth.AddDays(7);
currentMonth = startofthemonth.Month;
}
while (currentMonth == MonthNumber);
You can loop 7 times inside the constructor of everyweek and put you logic in there.您可以在 everyweek 的构造函数中循环 7 次并将逻辑放入其中。
Hope this helps with your issue!希望这对您的问题有所帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.