C#输出日历
用C#输出日历,此功能可用于Ajax方式列出计划日程相关的内容,由于是C#控制输出,可以方便加上自己需要的业务处理逻辑。
1.控制台输出:
- using System;
- namespace 控制台日历
- {
- class Program
- {
- public static void Main(string[] args)
- {
- string s = " ";
- Console.WriteLine("输入年份:");
- int nYear = int.Parse(Console.ReadLine());
- Console.WriteLine("输入月份:");
- int nMonth = int.Parse(Console.ReadLine());
- DateTime day1 = new DateTime(nYear,nMonth,1);
- Console.WriteLine("{0}/{1}",day1.Year,day1.Month);
- Console.WriteLine("日 一 二 三 四 五 六");
- int week1 =(int )day1.DayOfWeek;//获取当年当月1号的星期
- //Console.WriteLine("当月一号的星期{0}",week1);
- int lastday = day1.AddMonths(1).AddDays(-1).Day; //获取当月的最后一天
- for (int i = 0; i < week1; i++)
- Console.Write(s);//不能换行输出
- for (int i = 1; i <= lastday; i++)
- {
- Console.Write("{0:00} ", i);//按01 02 输出
- if ((i + week1) % 7 == 0)
- Console.WriteLine();
- }
- Console.WriteLine();
- Console.Write("Press any key to continue . . . ");
- Console.ReadKey(true);
- }
- }
- }
效果图:
2.Html表格输出:
- #region 生成表格日历
- /// <summary>
- /// 生成表格日历 index:月份偏量,用来查看上一月下一月
- /// </summary>
- /// <param name="index"></param>
- /// <returns></returns>
- public static string GetCalendarHtml(int index = 0)
- {
- DateTime day1 = new DateTime(DateTime.Now.AddMonths(index).Year, DateTime.Now.AddMonths(index).Month, 1);
- int week1 = (int)day1.DayOfWeek;//获取当年当月1号的星期
- int lastday = day1.AddMonths(1).AddDays(-1).Day; //获取当月的最后一天
- System.Text.StringBuilder builder = new System.Text.StringBuilder();
- builder.Append(string.Format("<table class='calendar_table'><caption><span style='cursor:pointer' class='prevMonth' onclick='javascript:changeMonth(-1)'>上一月</span><span class='currMonth'> {0}年{1}月</span><span style='cursor:pointer' class='nextMonth' onclick='javascript:changeMonth(1)'>下一月</span></caption>", DateTime.Now.AddMonths(index).Year, DateTime.Now.AddMonths(index).Month));
- builder.Append("<tr class='calendar_head'>");
- builder.Append("<td class='calendar_cell'>日</td>");
- builder.Append("<td class='calendar_cell'>一</td>");
- builder.Append("<td class='calendar_cell'>二</td>");
- builder.Append("<td class='calendar_cell'>三</td>");
- builder.Append("<td class='calendar_cell'>四</td>");
- builder.Append("<td class='calendar_cell'>五</td>");
- builder.Append("<td class='calendar_cell'>六</td>");
- builder.Append("</tr>");
- string emptyString = "<td class='calendar_cell'> </td>";
- if (week1 > 0)
- {
- builder.Append("<tr class='calendar_body'>");
- for (int i = 0; i < week1; i++)
- {
- builder.Append(emptyString);
- }
- }
- for (int i = 1; i <= lastday; i++)
- {
- string day = string.Format("{0:00} ", i);//按01 02 输出
- builder.Append(string.Format("<td class='calendar_cell'>{0}</td>", day));
- if ((i + week1) % 7 == 0)
- {
- builder.Append("</tr><tr class='calendar_body'>");
- }
- }
- builder.Append("</tr>");
- builder.Append("</table>");
- return builder.ToString();
- }
- #endregion
页面前台结合javascript实现ajax日历切换效果,只需用js改变函数中的index偏移量即可。