2008年3月9日 星期日

JavaScript 日期加減 及 日期相差

1.日期加減
<script language=javascript>
function addDate(dy,dmomth,dd,dh,dm,dadd){
var a = new Date(dy,dmomth,dd,dh,dm)
a = a.valueOf()
a = a + dadd * 1 * 60 * 60 * 1000
a = new Date(a)
return a;
}

var now = new Date();
var years = now.getYear();
var months = now.getMonth()+1;
var days = now.getDate();
var hours = now.getHours();
var minutes = now.getMinutes();

NextNow = addDate(years,months-1,days,hours,0,-1);
years = NextNow.getYear();
months = NextNow.getMonth()+1;
days = NextNow.getDate();
hours = NextNow.getHours();

</script>

2.日期相差

<script language=javascript>

Date.prototype.dateDiff = function(interval,objDate){
var dtEnd = new Date(objDate);
if(isNaN(dtEnd)) return undefined;
switch (interval) {
case "s":return parseInt((dtEnd - this) / 1000);
case "n":return parseInt((dtEnd - this) / 60000);
case "h":return parseInt((dtEnd - this) / 3600000);
case "d":return parseInt((dtEnd - this) / 86400000);
case "w":return parseInt((dtEnd - this) / (86400000 * 7));
case "m":return (dtEnd.getMonth()+1)+((dtEnd.getFullYear()-this.getFullYear())*12) - (this.getMonth()+1);
case "y":return dtEnd.getFullYear() - this.getFullYear();
}
}

var sDT = new Date("2004/05/20 07:30:00");
var eDT = new Date("2005/05/20 08:32:02");
document.writeln("秒差 : "+sDT.dateDiff("s",eDT)+"<br>");
document.writeln("分差 : "+sDT.dateDiff("n",eDT)+"<br>");
document.writeln("時差 : "+sDT.dateDiff("h",eDT)+"<br>");
document.writeln("日差 : "+sDT.dateDiff("d",eDT)+"<br>");
document.writeln("週差 : "+sDT.dateDiff("w",eDT)+"<br>");
document.writeln("月差 : "+sDT.dateDiff("m",eDT)+"<br>");
document.writeln("年差 : "+sDT.dateDiff("y",eDT)+"<br>");
</script>