您的位置:首页 > 编程语言

趣味编程:打印日历

2015-10-29 13:39 330 查看
趣味编程:打印日历

using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;

namespace ConsoleApplication2
{
static class StringExtensions
{
public static string CenterString(this string stringToCenter, int totalLength)
{
return stringToCenter.PadLeft(((totalLength - stringToCenter.Length) / 2) + stringToCenter.Length)
.PadRight(totalLength);
}
}

class Program
{
static void Main(string[] args)
{
var year = DateTime.Now.Year;
var dts = new List<DateTime>();
for (DateTime dt = new DateTime(year, 1, 1), dt_end = new DateTime(year + 1, 1, 1); dt != dt_end; dt = dt.AddDays(1))
dts.Add(dt);
var grps = dts.GroupBy(dt => dt.Month,
(k, g) => g.GroupBy(dt => CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(dt, CalendarWeekRule.FirstDay, DayOfWeek.Sunday),
(k2, g2) => g2.ToList()).ToList()).ToList();
grps.ForEach(g => {
Console.WriteLine(g[0][0].ToString("Y").CenterString(21));
g.ForEach(g2 =>
Console.WriteLine(g2[0].Day == 1 ? "{0,21}" : "{0,-21}", string.Join("", g2.Select(dt => string.Format("{0,3}", dt.Day))))
);
});
}
}
}
/*
2015年1月
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
2015年2月
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
...
...
...
2015年12月
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
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: