日期:2014-05-17 浏览次数:21074 次
原文:http://hi.baidu.com/wosxiaoyao/item/1837b791fde008d57b7f014f
其中的输出日历类Calendar如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; namespace xianshirili { public class Calendar { public void PrintCalendar(int year, int month,TextBox textbox) { StringBuilder builder = new StringBuilder(); builder.Append(" 日 一 二 三 四 五 六\r\n"); int hawdays = GetWeeksOfDate(year, month, 1); //这个月的第一天星期几 int days = GetDaysOfMonth(year, month); //获取想要输出月份的天数 for (int i = 1; i <= hawdays * 3; i++) //打印第一排前面的空格 { builder.Append(" "); } for (int j = 1; j <= days; j++) { if (j <= 9) { builder.Append(" "); builder.Append(" "); builder.Append(Convert.ToString(j)); } // Console.Write(" {0}", j); if (j >= 10) { builder.Append(" "); builder.Append(Convert.ToString(j)); } // Console.Write(" {0}", j); if ((hawdays + j) % 7 == 0) builder.Append("\r\n"); } textbox.Text = builder.ToString(); } // 计算当前日期以前的天数 public static int GetDaysOfDate(int year, int month, int day) { int days = 0; for (int i = 1980; i < year; i++) { days += GetDaysOfYears(i); } for (int i = 1; i < month; i++) { days += GetDaysOfMonth(year, i); } days = days + day - 1; return days; } //计算星期,返回具体的某一天星期几 值为0~6 public static int GetWeeksOfDate(int year, int month, int day) { int weeks = GetDaysOfDate(year, month, day); return (weeks + 2) % 7; } // 判断是否闰年并返回当年总天数 public static bool LeapYear(int year) { return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0); } //判断月份,返回当月的天数 public static int GetDaysOfMonth(int year, int month) { int days = 30; switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: days = 31; break; case 4: case 6: case 9: case 11: days = 30; break; case 2: days = LeapYear(year) ? 29 : 28; break; default: days = 30; break; } return days; } //根据年,判断是否闰年并返回一年里有几天 public static int GetDaysOfYears(int year) { return LeapYear(year) ? 366 : 365; } } }经过一翻改写测试,最终实现同样的功能,代码精简了一半多,如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; public class Calendar { public void PrintCalendar(int year, int month, TextBox textbox) { StringBuilder builder = new StringBuilder(); builder.Append(" 日 一 二 三 四 五 六\r\n"); int hawdays = GetWeeksOfDate(year, month, 1); //这个月的第一天星期几 int days = GetDaysOfMonth(year, month); //获取想要输出月份的天数 for (int i = 1; i <= hawdays * 3; i++) //打印第一排前面的空格 { builder.Append(" "); } for (int j = 1; j <= days; j++) {