標題有點繞,其實意思就是根據系統當前時間,獲取n分鍾或n小時或n個月后的時間。
例如:當前時間下,獲取10分鍾后的時間。
var date=new Date(); //1. js獲取當前時間 var min=date.getMinutes(); //2. 獲取當前分鍾 date.setMinutes(min+10); //3. 設置當前時間+10分鍾:把當前分鍾數+10后的值重新設置為date對象的分鍾數 var y = date.getFullYear(); var m = (date.getMonth() + 1) < 10 ? ("0" + (date.getMonth() + 1)) : (date.getMonth() + 1); var d = date.getDate() < 10 ? ("0" + date.getDate()) : date.getDate(); var h = date.getHours() < 10 ? ('0' + date.getHours()) : date.getHours() var f = date.getMinutes() < 10 ? ('0' + date.getMinutes()) : date.getMinutes() var s = date.getSeconds() < 10 ? ('0' + date.getseconds()) : date.getSeconds() var formatdate = y+'-'+m+'-'+d + " " + h + ":" + f + ":" + s; console.log(formatdate) // 獲取10分鍾后的時間,格式為yyyy-mm-dd h:f:s
同理,設置30分鍾,60分鍾或1個小時,5個小時,可以將小時轉換為分鍾,然后獲取當前分鍾再加上需要設置的時間即可。
獲取1個月后的日期:
var date=new Date(); date.setMonth(date.getMonth()+1); var y = date.getFullYear(); var m = (date.getMonth() + 1) < 10 ? ("0" + (date.getMonth() + 1)) : (date.getMonth() + 1); var d = date.getDate() < 10 ? ("0" + date.getDate()) : date.getDate(); var h = date.getHours() < 10 ? ('0' + date.getHours()) : date.getHours() var f = date.getMinutes() < 10 ? ('0' + date.getMinutes()) : date.getMinutes() var s = date.getSeconds() < 10 ? ('0' + date.getseconds()) : date.getSeconds() var formatwdate = y+'-'+m+'-'+d + " " + h + ":" + f + ":" + s; console.log('formatwdate', formatwdate)
同理獲取n個月后或n個月前的日期都是如此