貌似最近很流行这个,就写了个js函数实现之
<!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>
最近研究android,用java写的实现方法
public static String getTimeDiff(Date date) {
Calendar cal = Calendar.getInstance();
long diff = 0;
Date dnow = cal.getTime();
String str = "";
diff = dnow.getTime() - date.getTime();
if (diff > 2592000000L) {//30 * 24 * 60 * 60 * 1000=2592000000 毫秒
str="1个月前";
} else if (diff > 1814400000) {//21 * 24 * 60 * 60 * 1000=1814400000 毫秒
str="3周前";
} else if (diff > 1209600000) {//14 * 24 * 60 * 60 * 1000=1209600000 毫秒
str="2周前";
} else if (diff > 604800000) {//7 * 24 * 60 * 60 * 1000=604800000 毫秒
str="1周前";
} else if (diff > 86400000) { //24 * 60 * 60 * 1000=86400000 毫秒
//System.out.println("X天前");
str=(int)Math.floor(diff/86400000f) + "天前";
} else if (diff > 18000000 ) {//5 * 60 * 60 * 1000=18000000 毫秒
//System.out.println("X小时前");
str=(int)Math.floor(diff/18000000f) + "小时前";
} else if (diff > 60000) {//1 * 60 * 1000=60000 毫秒
//System.out.println("X分钟前");
str=(int)Math.floor(diff/60000) +"分钟前";
}else{
str=(int)Math.floor(diff/1000) +"秒前";
}
return str;
}
网上有用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秒前";
}
}