//時間差 function GetTime(time) {//di做爲一個變量傳進來 //若是時間格式是正確的,那下面這一步轉化時間格式就能夠不用了 var dateBegin = new Date(time.replace(/-/g, "/"));//將-轉化爲/,使用new Date var dateEnd = new Date();//獲取當前時間 var dateDiff = dateEnd.getTime() - dateBegin.getTime();//時間差的毫秒數 var dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000));//計算出相差天數 var leave1 = dateDiff % (24 * 3600 * 1000) //計算天數後剩餘的毫秒數 var hours = Math.floor(leave1 / (3600 * 1000))//計算出小時數 //計算相差分鐘數 var leave2 = leave1 % (3600 * 1000) //計算小時數後剩餘的毫秒數 var minutes = Math.floor(leave2 / (60 * 1000))//計算相差分鐘數 //計算相差秒數 var leave3 = leave2 % (60 * 1000) //計算分鐘數後剩餘的毫秒數 var seconds = Math.round(leave3 / 1000); if (dayDiff >= 7) { return time.replace(/-/g, "/"); } if (dayDiff > 0) { return dayDiff + "天前"; } if (hours > 0) { return hours + "小時前"; } if (minutes > 0) { return minutes + "分鐘前"; } return seconds + "秒前"; //console.log(" 相差 " + dayDiff + "天 " + hours + "小時 " + minutes + " 分鐘" + seconds + " 秒") //console.log(dateDiff + "時間差的毫秒數", dayDiff + "計算出相差天數", leave1 + "計算天數後剩餘的毫秒數", hours + "計算出小時數", minutes + "計算相差分鐘數", seconds + "計算相差秒數"); }