当前位置:网站首页>[JS] obtain the N days before and after the current time or the n months before and after the current time (hour, minute, second, year, month, day)

[JS] obtain the N days before and after the current time or the n months before and after the current time (hour, minute, second, year, month, day)

2022-07-07 01:10:00 Cold hope

There are many ways , But the principle is to obtain the current time first and then add or subtract the time difference

1. Plus or minus timestamp

new Date() You can pass in a timestamp after addition and subtraction

let nowDate = new Date();
// 3 Seconds ago 
let nextDate = new Date(nowDate.getTime() - 3 * 1000); 
// 3 Minutes ago 
let nextDate = new Date(nowDate.getTime() - 3 * 60 * 1000); 
// 24 Hours milliseconds 
let dayStamp = 24 * 60 * 60 * 1000  
//  front 1 God 
let preDate = new Date(nowDate.getTime() - dayStamp);
//  after 3 God 
let nextDate = new Date(nowDate.getTime() + 3 * dayStamp);

2.api Set up

Date There are many objects get and set Methods get and set the hour, minute, second, year, day

// 3 Seconds ago 
let choiceStartDt = new Date(new Date().setSeconds((new Date().getSeconds() - 3)))
// 7 Seconds later 
let choiceStartDt = new Date(new Date().setSeconds((new Date().getSeconds() + 7)))
// 3 Minutes ago 
let choiceStartDt = new Date(new Date().setMinutes((new Date().getMinutes() - 3)))
// 3 An hour ago 
let choiceStartDt = new Date(new Date().setHours((new Date().getHours() - 3)))
//  front 1 God 
let choiceStartDt = new Date(new Date().setDate((new Date().getDate() - 1)))
//  front 1 Months 
let choiceStartDt = new Date(new Date().setMonth((new Date().getMonth() - 1)))	
//  front 3 year 
let choiceStartDt = new Date(new Date().setFullYear((new Date().getFullYear() - 3)))
原网站

版权声明
本文为[Cold hope]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207061718365377.html