不管是設置相對當前時間有多久時間差的時間,思路:先獲取當前時間的時間戳,再根據需求加減時間獲得新的時間戳,然后取年月日與時分秒。實例:
// 設置默認時間——先轉化為毫秒數,加上 24 小時的毫秒數,再轉化回來 function setTime () { let t = new Date().getTime() + 24 * 60 * 60 * 1000; //24小時 * 60分鍾 * 60秒 * 1000 let d = new Date(t); let theMonth = d.getMonth() + 1; let theDate = d.getDate(); let theHours = d.getHours(); let theMinutes = d.getMinutes(); if (theMonth < 10) { theMonth = '0' + theMonth } if (theDate < 10) { theDate = '0' + theDate } if (theHours < 10) { theHours = '0' + theHours } if (theMinutes < 10) { theMinutes = '0' + theMinutes } let date = d.getFullYear() + '-' + theMonth + '-' + theDate let time = theHours + ':' + theMinutes let Spare = date + ' ' + time console.log(date) console.log(time) console.log(Spare) }