62,074
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
namespace Test
{
class Program
{
static void Main(string[] args)
{
var samples = new string[] {
"2013年11月", "2013年12月", "2014年1月","2014年2月","2014年3月","2014年4月","2014年12月",
"201401","201402","201403","201404"
};
var results = Convert(samples);
foreach (var item in results)
{
Console.WriteLine(item);
}
}
static IEnumerable<string> Convert(IEnumerable<string> dates)
{
var formats = new string[] { "yyyy年M月", "yyyyMM" };
var sampleDates = dates.Select(
str => DateTime.ParseExact(str, formats, null, DateTimeStyles.None)
)
.Distinct()
.OrderBy(d => d);
if (sampleDates.Any())
{
DateTime? start = null;
DateTime? cursor = start;
foreach (var item in sampleDates)
{
if (start == null)
{
start = cursor = item;
continue;
}
if ((item - cursor.Value).TotalDays < 32d
&& item.Year == cursor.Value.Year)
{
cursor = item;
}
else
{
if (cursor.Value == start.Value)
{
yield return string.Format("{0:yyyy年M月}", start);
}
else
{
yield return string.Format("{0:yyyy}年({0:%M}-{1:%M}月)", start, cursor);
}
cursor = start = item;
}
}
if (cursor != null)
{
if (cursor.Value == start.Value)
{
yield return string.Format("{0:yyyy年M月}", start);
}
else
{
yield return string.Format("{0:yyyy}年({0:%M}-{1:%M}月)", start, cursor);
}
}
}
}
}
}
输出:
2013年(11-12月)
2014年(1-4月)
2014年12月