改进这段代码--关于时间比较
//这段代码是获取每个数据的创建时间,再与当前时间做比较,从而把页面改成比较友好的时间显示如:昨天 12:00:00或前4小时,这段代码我总觉得比较乱,希望高手能帮我理理,让它变得更轻巧些
public static string GetCompareDate(DateTime strDate)//strDate是数据的创建时间
{
//刚刚,5分钟前,10分钟前,半小时前,1小时前,2小时前,3小时前,4小时前
//5小时前,昨天'几点',前天'几点',再超过就显示完整时间
DateTime now = DateTime.Now; //获取当前时间
string showTime = "";
if (strDate.ToString("yyyy-MM-dd") == "0001-01-01" || String.IsNullOrEmpty(strDate.ToString("yyyy-MM-dd")))
{
showTime = "还没人发表过!";
}
else
{
#region 过去
if (strDate.Date.CompareTo(now.Date) < 0)
{
//同年
if (strDate.Year.CompareTo(now.Year) == 0)
{
//同月
if (strDate.Month.CompareTo(now.Month) == 0)
{
//前天
if (strDate.AddDays(2).CompareTo(now.Date) == 0)
{
showTime = "前天 " + strDate.ToString("HH:mm:ss");
}
//早于前天发布的
else if (strDate.AddDays(2).CompareTo(now.Date) < 0)
{
showTime = strDate.ToString("yyyy-MM-dd HH:mm:ss");
}
//昨天
else
{
showTime = "昨天 " + strDate.ToString("HH:mm:ss");
}
}
else
{
showTime = strDate.ToString("yyyy-MM-dd HH:mm:ss");
}
}
else
{
showTime = strDate.ToString("yyyy-MM-dd HH:mm:ss");
}
}
#endregion
#region 今天
else if (strDate.Date.CompareTo(now.Date) == 0)
{
DateTime nowHour = DateTime.Parse(now.ToString("HH:mm:ss"));
//5小时前
if (strDate.AddHours(5).CompareTo(nowHour) == 0)
{
showTime = "5小时前";
}
else if (strDate.AddHours(5).CompareTo(nowHour) < 0)
{
showTime = "今天 " + strDate.ToString("HH:mm:ss");
}
else
{
//4小时前
if (strDate.AddHours(5).CompareTo(nowHour) < 0 || strDate.AddHours(4).CompareTo(nowHour) <=0)
{
showTime = "4小时前";
}
else
{
//3小时前