<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE> New Document </tITLE> <META NAME="Generator" CONTENT="EditPlus"> <META NAME="Author" CONTENT=""> <META NAME="Keywords" CONTENT=""> <META NAME="Description" CONTENT=""> <script language="javascript"> 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")); </script> </hEAD> <BODY > </bODY> </hTML>
[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秒前";
}
}