I would like to output all days of the current month at once. The format (e.g. for August) should be Monday - 01.08.22
to Wednesday - 31.08.22
. I would like to transfer each individual day into an Excel list. My question is how I can output the individual days of the current month programmatically.
I can imagine using the library DateTime moment = new DateTime();
That should be simple enough to do with the help of DateTime.DaysInMonth
.
First we'll use the starting DateTime
to get the year and month number to create a new DateTime
for the first day of the month.
Next we'll get the number of days in the month.
We'll then loop from 0 to [daysInMonth] (exclusive) adding that number of days to the startOfMonth date.
Finally, for each we can convert it to a string in the desired format.
DateTime startTime = DateTime.Now;
DateTime startOfMonth = new DateTime(startTime.Year, startTime.Month, 1);
int daysInMonth = DateTime.DaysInMonth(startTime.Year, startTime.Month);
for (int i = 0; i < daysInMonth; ++i)
{
DateTime currentDate = startOfMonth.AddDays(i);
Console.WriteLine(currentDate.ToString("dddd - dd.MM.yy", CultureInfo.InvariantCulture));
}
Output for today:
Monday - 01.08.22
Tuesday - 02.08.22
Wednesday - 03.08.22
Thursday - 04.08.22
Friday - 05.08.22
Saturday - 06.08.22
Sunday - 07.08.22
Monday - 08.08.22
Tuesday - 09.08.22
Wednesday - 10.08.22
Thursday - 11.08.22
Friday - 12.08.22
Saturday - 13.08.22
Sunday - 14.08.22
Monday - 15.08.22
Tuesday - 16.08.22
Wednesday - 17.08.22
Thursday - 18.08.22
Friday - 19.08.22
Saturday - 20.08.22
Sunday - 21.08.22
Monday - 22.08.22
Tuesday - 23.08.22
Wednesday - 24.08.22
Thursday - 25.08.22
Friday - 26.08.22
Saturday - 27.08.22
Sunday - 28.08.22
Monday - 29.08.22
Tuesday - 30.08.22
Wednesday - 31.08.22