js中日期比较排序

时间:2021-11-12 18:06:22

js中日期比较排序

<html>
<head>
<title>blog</title>
<script type="text/javascript">
function Blog(body,date){//Blog对象的构造函数
this.body=body;
this.date=date;
}
var blog=[new Blog("11111",new Date("05/01/2016")),new Blog("22222",new Date("05/05/2016")),new Blog("33333",new Date("05/03/2016")),new Blog("44444",new Date("05/07/2016"))];
blog.sort(function(blog1,blog2){//对blog数组进行排序,最新日期放在最前面
return blog2.date-blog1.date;
});
function showBlog(numEntries){//进入网页就加载该函数或者点击按钮调用该函数
if(!numEntries)//没有值时则显示全部的Blog对象
numEntries=blog.length;
var i=0,blogText="";
while(i<blog.length&&i<numEntries){
if(i%2==0)
blogText+="<p style='background-color:#EEEEEE'>";
else
blogText+="<p>";
//blogText+="<strong>"+blog[i].date+"</strong><br />"+blog[i].body+"</p>";
blogText+="<strong>"+(blog[i].date.getMonth()+1)+"/"+blog[i].date.getDate()+"/"+blog[i].date.getFullYear()+"</strong><br />"+blog[i].body+"</p>";
i++;
}
document.getElementById("blog").innerHTML=blogText;
}
</script>
</head>
<body onload="showBlog(1);">
<h3>THE BLOG</h3>
<div id="blog"></div>
<input type="button" id="showAll" value="show all" onclick="showBlog();" />
<input type="button" id="show2" value="show2" onclick="showBlog(2);" />
</body>
</html>