2016年12月21日 星期三

自製JavaScript dateDiff函數

在Google Spreadsheet上寫JavaScript真的很多要注意,JavaScript沒有dateDiff() 這樣的日期時間處理函數,找了一下網路剛好有,順道記錄一下。
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("2011/08/01 08:00:00");  //必要項。sDT- 這是在計算中想要使用的第一個日期/時間值。 
var eDT = new Date("2011/08/02 09:10:50");  //必要項。eDT- 這是在計算中想要使用的第二個日期/時間值。 

sDT.dateDiff("s", eDT);
sDT.dateDiff("n", eDT);
sDT.dateDiff("h", eDT);
sDT.dateDiff("d", eDT);
sDT.dateDiff("w", eDT);
sDT.dateDiff("m", eDT);
sDT.dateDiff("y", eDT);