I'm learning C# and I wanted to make a calendar to learn 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.
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
CodePudding user response:
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.
Hope this helps with your issue!