js 設定當前時間的後20分鐘、後一小時、前一天等等相對時間
阿新 • • 發佈:2018-12-19
不管是設定相對當前時間有多久時間差的時間,統一思路為:先獲取當前時間的時間戳,再根據需求加減時間獲得新的時間戳,然後取年月日與時分秒。例項如下:
// 設定預設時間——先轉化為毫秒數,加上 20 分鐘的毫秒數,再轉化回來 setDefaultTime() { let t = new Date().getTime() + 1200000; 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) },