要添加时间,请获取当前日期,然后以毫秒为单位添加特定的时间量,然后使用以下值创建一个新日期:
// get the current date & time (as milliseconds since Epoch)
const currentTimeAsMs = Date.now();
// Add 3 days to the current date & time
// I'd suggest using the calculated static value instead of doing inline math
// I did it this way to simply show where the number came from
const adjustedTimeAsMs = currentTimeAsMs + (1000 * 60 * 60 * 24 * 3);
// create a new Date object, using the adjusted time
const adjustedDateObj = new Date(adjustedTimeAsMs);
进一步解释这一点;原因dataObj.setMilliseconds()
不起作用是因为它将 dateobj 的毫秒属性设置为指定值(0 到 999 之间的值)。它不会将对象的日期设置为毫秒。
// assume this returns a date where milliseconds is 0
dateObj = new Date();
dateObj.setMilliseconds(5);
console.log(dateObj.getMilliseconds()); // 5
// due to the set value being over 999, the engine assumes 0
dateObj.setMilliseconds(5000);
console.log(dateObj.getMilliseconds()); // 0
参考:
Date.now()
new Date()
Date.setMilliseconds()