private static string[] nearDayName = { "三天前", "前天", "昨天", "今天", "明天", "后天", "三天后" };
public static String ToNearDayName(DateTime dt)
{
int days = (dt.Year * 365 + dt.DayOfYear) - (DateTime.Now.Year * 365 + DateTime.Now.DayOfYear);
return ToNearDayName(days);
} public static String ToNearDayName(int days)
{
days += 3;
days = Math.Max(days, 0);
days = Math.Min(days, 6);
return nearDayName[days];
}
我发明了以上方法来返回昨天今天前天等等,但是还是不太精确,遇到闫年的时候还是会出丑.谁能给个完善的方案.
/// 取得与当前时间的间隔(MM-dd hh:mm-刚刚更新)
/// </summary>
public static string GetTimeSpacing(DateTime time1, string format)
{
string strTime = "";
DateTime date1 = DateTime.Now;
DateTime date2 = time1;
TimeSpan dt = date1 - date2; // 相差天数
int days = dt.Days;
// 时间点相差小时数
int hours = dt.Hours;
// 相差总小时数
double Minutes = dt.Minutes;
// 相差总秒数
int second = dt.Seconds; if (second < 0) { second = 0; }
if (days == 0 && hours == 0 && Minutes == 0)
{
strTime = "刚刚更新";
}
else if (days == 0 && hours == 0)
{
strTime = Minutes + "分钟前";
}
else if (days == 0)
{
strTime = hours + "小时前";
}
else
{
if(format=="MM-dd hh:mm")
strTime = time1.ToString("MM-dd hh:mm");
else if(format=="yyyy年MM月dd日")
strTime = time1.ToString("yyyy年MM月dd日");
else if (format == "yy-MM-dd")
strTime = time1.ToString("yy-MM-dd");
else if (format == "MM-dd")
strTime = time1.ToString("MM-dd");
else if (format == "MM月dd日")
strTime = time1.ToString("MM月dd日");
}
return strTime;
} 给你做下参考
得出来的结果是只有1秒钟,而不是昨天和今天这样的效果
http://www.cnblogs.com/rodney/archive/2007/09/30/911570.html
可能对你有帮助。