JavaScript 中 new Date() 时间使用
JavaScript 中 new Date() 时间使用
01)JavaScript获取当前时间加上10分钟
遇到整点可以累加到下一时间
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
// JavaScript获取当前时间加上10分钟 function dateAdd(dStr, interval = 10) { let d = new Date( dStr.substring(0, 4), dStr.substring(5, 7) - 1, dStr.substring(8, 10), dStr.substring(11, 13), dStr.substring(14, 16), dStr.substring(17, 19) ); d.setTime(d.getTime() + interval * 60 * 1000); //小于10前面补0 let getMonth = (d.getMonth() + 1) < 10 ? "0" + (d.getMonth() + 1) : d.getMonth() + 1; let getDate = d.getDate() < 10 ? "0" + (d.getDate()) : d.getDate(); let getHours = d.getHours() < 10 ? "0" + (d.getHours()) : d.getHours(); let getMinutes = d.getMinutes() < 10 ? "0" + (d.getMinutes()) : d.getMinutes(); return d.getFullYear() + "-" + getMonth + "-" + getDate + " " + getHours + ":" + getMinutes; } console.log(dateAdd('2022-02-20 08:00'))
02)JavaScript获取当前时间减去10分钟
遇到整点可以累加到下一时间
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
// JavaScript获取当前时间减去10分钟 function dateDecrease(dStr,interval = 10) { let d = new Date( dStr.substring(0, 4), dStr.substring(5, 7) - 1, dStr.substring(8, 10), dStr.substring(11, 13), dStr.substring(14, 16), dStr.substring(17, 19) ); d.setTime(d.getTime() - interval * 60 * 1000); //小于10前面补0 let getMonth = (d.getMonth() + 1) < 10 ? "0" + (d.getMonth() + 1) : d.getMonth() + 1; let getDate = d.getDate() < 10 ? "0" + (d.getDate()) : d.getDate(); let getHours = d.getHours() < 10 ? "0" + (d.getHours()) : d.getHours(); let getMinutes = d.getMinutes() < 10 ? "0" + (d.getMinutes()) : d.getMinutes(); return d.getFullYear() + "-" + getMonth + "-" + getDate + " " + getHours + ":" + getMinutes; } console.log(dateDecrease('2022-02-04 08:00'))
03)常见获取时间
JavaScript中获取的时间戳单位都是毫秒,
获取一天开始时间戳,获取一天结束时间戳,当前时间戳
// 当天00点00分00秒 时间戳 1659974400000 new Date(new Date().toLocaleDateString()).getTime() // 当天23点59分59秒 时间戳 1660060799999 new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1 // 当前时间戳 1659976187168 new Date().getTime() // 当前日期 '2022/8/9' new Date().toLocaleDateString() // 当前时间 '2022/8/9 00:29:14' new Date().toLocaleString()