JAVASCRIPT 实现普通日期转换多少小时前、多少分钟前、多少秒
New Document
function stringToDateTime(postdate)
{
var second = 1000;
var minutes = second*60;
var hours = minutes*60;
var days = hours*24;
var months = days*30;
var twomonths = days*365;
var myDate = new Date(Date.parse(postdate));
if (isNaN(myDate))
{
myDate =new Date(postdate.replace(/-/g, "/"));
}
var nowtime = new Date();
var longtime =nowtime.getTime()- myDate.getTime();
var showtime = 0;
if( longtime > months*2 )
{
return postdate;
}
else if (longtime > months)
{
return "1个月前";
}
else if (longtime > days*7)
{
return ("1周前");
}
else if (longtime > days)
{
return(Math.floor(longtime/days)+"天前");
}
else if ( longtime > hours)
{
return(Math.floor(longtime/hours)+"小时前");
}
else if (longtime > minutes)
{
return(Math.floor(longtime/minutes)+"分钟前");
}
else if (longtime > second)
{
return(Math.floor(longtime/second)+"秒前");
}else
{
return(longtime+" error ");
}
}
document.write(stringToDateTime("2009-05-24 15:05:00"));
[Ctrl+A 全选 注:如需引入外部Js需刷新才能执行]
网上有用C#后台实现的方法,为方便查看就转贴到下面吧:)
代码如下:
public string DateStringFromNow(DateTime dt)
{
TimeSpan span = DateTime.Now - dt;
if (span.TotalDays >60)
{
return dt.ToShortDateString();
}
else
if ( span.TotalDays >30 )
{
return
"1个月前";
}
else
if (span.TotalDays >14)
{
return
"2周前";
}
else
if (span.TotalDays >7)
{
return
"1周前";
}
else
if (span.TotalDays >1)
{
return
string.Format("{0}天前", (int)Math.Floor(span.TotalDays));
}
else
if (span.TotalHours >1)
{
return
string.Format("{0}小时前", (int)Math.Floor(span.TotalHours));
}
else
if (span.TotalMinutes >1)
{
return
string.Format("{0}分钟前", (int)Math.Floor(span.TotalMinutes));
}
else
if (span.TotalSeconds >=1)
{
return
string.Format("{0}秒前", (int)Math.Floor(span.TotalSeconds));
}
else
{
return
"1秒前";
}
}