所以我们正在寻找如何在C#中编写日历的方法,如果您使用的是asp.net,这很容易。但是,我使用控制台应用程序是因为我需要这样做。现在编码一个月并不坏,但我无法弄清楚如何编码整年(1月至12月)。
namespace ConsoleApplication6
{
class Program
{
static void Main(string[] args)
{
int current = 0;
int skip = 0;
int day = 1;
int endDay = 31;
string line = " Sun Mon Tue Wed Thu Fri Sat";
Console.WriteLine(line);
line = "";
while (skip < current)
{
line += " ";
skip++;
}
while (day <= endDay)
{
while (current < 7 && day <= endDay)
{
line += String.Format("{0,4}", day);
current++;
day++;
}
Console.WriteLine(line);
line = "";
current = 0;
}
Console.ReadLine();
}
}
}
这样做之后会显示一个月的日历,所以问题是如何在仍然使用控制台应用程序和我已经拥有的代码的同时显示全年日历?
答案 0 :(得分:1)
你可以这样做。我试图添加注释以供解释:
static void Main(string[] args)
{
// Loop 12 times (once for each month)
for (int i = 1; i < 13; i++)
{
// Get the first day of the current month
var month = new DateTime(2017, i, 1);
// Print out the month, year, and the days of the week
// headingSpaces is calculated to align the year to the right side
var headingSpaces = new string(' ', 16 - month.ToString("MMMM").Length);
Console.WriteLine($"{month.ToString("MMMM")}{headingSpaces}{month.Year}");
Console.WriteLine(new string('-', 20));
Console.WriteLine("Su Mo Tu We Th Fr Sa");
// Get the number of days we need to leave blank at the
// start of the week.
var padLeftDays = (int)month.DayOfWeek;
var currentDay = month;
// Print out the day portion of each day of the month
// iterations is the number of times we loop, which is the number
// of days in the month plus the number of days we pad at the beginning
var iterations = DateTime.DaysInMonth(month.Year, month.Month) + padLeftDays;
for (int j = 0; j < iterations; j++)
{
// Pad the first week with empty spaces if needed
if (j < padLeftDays)
{
Console.Write(" ");
}
else
{
// Write the day - pad left adds a space before single digit days
Console.Write($"{currentDay.Day.ToString().PadLeft(2, ' ')} ");
// If we've reached the end of a week, start a new line
if ((j + 1) % 7 == 0)
{
Console.WriteLine();
}
// Increment our 'currentDay' to the next day
currentDay = currentDay.AddDays(1);
}
}
// Put a blank space between months
Console.WriteLine("\n");
}
Console.Write("\nDone!\nPress and key to exit...");
Console.ReadKey();
}
输出: