|
C#: command line calendarThis is a C# version of the PHP command line calendar. The program prints the days of the current month and highlights the current day. It was developed against .NET 7, which allows top-level statements - that's why the familiar boiler plate code is missing. int colWidth = 4; // can be changed but don't make less than 2
// Print month and year
Console.WriteLine(DateTime.Today.ToString("MMMM yyyy"));
// Print days of the week header (Mo to Su)
Console.WriteLine("Mo{0}Tu{0}We{0}Th{0}Fr{0}Sa{0}Su{0}", string.Concat(Enumerable.Repeat(" ", colWidth - 2)));
// Values for today's date
var currentDay = DateTime.Today.Day;
var currentMonth = DateTime.Today.Month;
var currentYear = DateTime.Today.Year;
// Number of days in the month
var numDays = DateTime.DaysInMonth(currentYear, currentMonth);
// Loop through all days in the month
for (int day = 1; day <= numDays; day++)
{
int dayOfWeek = (int)new DateTime(currentYear, currentMonth, day).DayOfWeek; // 0 (Sunday) - 6 (Saturday)
dayOfWeek = dayOfWeek == 0 ? 7 : dayOfWeek; // use 7 for Sunday instead of 0
if (day == 1)
{
// Print any leading spaces required for the first day of the month
var spaces = (dayOfWeek - 1) * colWidth;
Console.Write(string.Concat(Enumerable.Repeat(" ", spaces)));
}
// Highlight the current day
if (day == currentDay)
Console.ForegroundColor = ConsoleColor.Green;
// Print the current day number plus required padding
Console.Write(day + (day < 10 ? " " : "") + string.Concat(Enumerable.Repeat(" ", colWidth - 2)));
// Reset text color
if (day == currentDay)
Console.ResetColor();
// Start a new line after each Sunday
if (dayOfWeek == 7)
Console.WriteLine();
}
Sample output: October 2023
Mo Tu We Th Fr Sa Su
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
|