#region 时间转文本
public static string ToRead(this DateTime src)
{
return ToRead(src as DateTime?);
}
public static string ToRead(this DateTime? src)
{
string result = null;
if (src.HasValue)
{
result = DateTimeToStr2(src.Value);
}
return result;
}
private static string DateTimeToStr1(DateTime src)
{
string result = null;
TimeSpan timeSpan = DateTime.Now - src;
if (((int)timeSpan.TotalDays) > 365) //大于一年的
{
int years = (int)timeSpan.TotalDays / 365;
//if (timeSpan.TotalDays % 365 > 0) years++;
result = string.Format("{0}年之前", years);
}
else if (((int)timeSpan.TotalDays) > 30) //大于一个月的
{
int months = (int)timeSpan.TotalDays / 30;
//if (timeSpan.TotalDays % 30 > 0) months++;
result = string.Format("{0}个月前", months);
}
else if (((int)timeSpan.TotalDays) > 7) //大于一周的
{
int weeks = (int)timeSpan.TotalDays / 7;
//if (timeSpan.TotalDays % 7 > 0) weeks++;
result = string.Format("{0}周前", weeks);
}
else if (((int)timeSpan.TotalDays) > 0) //大于 0 天的
{
result = string.Format("{0}天前", (int)timeSpan.TotalDays);
}
else if (((int)timeSpan.TotalHours) > 0) //一小时以上的
{
result = string.Format("{0}小时", (int)timeSpan.TotalHours);
}
else if (((int)timeSpan.TotalMinutes) > 0) //一分钟以上的
{
result = string.Format("{0}分钟前", (int)timeSpan.TotalMinutes);
}
else if (((int)timeSpan.TotalSeconds) >= 0 && ((int)timeSpan.TotalSeconds) <= 60) //一分钟内
{
result = "刚刚";
}
else
{
result = src.ToString("yyyy-MM-dd HH:mm:ss");
}
return result;
}
private static string DateTimeToStr2(DateTime src)
{
string result = null;
long currentSecond = (long)(DateTime.Now - src).TotalSeconds;
long minSecond = 60; //60s = 1min
long hourSecond = minSecond * 60; //60*60s = 1 hour
long daySecond = hourSecond * 24; //60*60*24s = 1 day
long weekSecond = daySecond * 7; //60*60*24*7s = 1 week
long monthSecond = daySecond * 30; //60*60*24*30s = 1 month
long yearSecond = daySecond * 365; //60*60*24*365s = 1 year
if (currentSecond >= yearSecond)
{
int year = (int)(currentSecond / yearSecond);
result = string.Format("{0}年前", year);
}
else if (currentSecond < yearSecond && currentSecond >= monthSecond)
{
int month = (int)(currentSecond / monthSecond);
result = string.Format("{0}个月前", month);
}
else if (currentSecond < monthSecond && currentSecond >= weekSecond)
{
int week = (int)(currentSecond / weekSecond);
result = string.Format("{0}周前", week);
}
else if (currentSecond < weekSecond && currentSecond >= daySecond)
{
int day = (int)(currentSecond / daySecond);
result = string.Format("{0}天前", day);
}
else if (currentSecond < daySecond && currentSecond >= hourSecond)
{
int hour = (int)(currentSecond / hourSecond);
result = string.Format("{0}小时前", hour);
}
else if (currentSecond < hourSecond && currentSecond >= minSecond)
{
int min = (int)(currentSecond / minSecond);
result = string.Format("{0}分钟前", min);
}
else if (currentSecond < minSecond && currentSecond >= 0)
{
result = "刚刚";
}
else
{
result = src.ToString("yyyy-MM-dd HH:mm:ss");
}
return result;
}
#endregion