Trying to add 3 days in Milliseconds to current Date
Use this code
var dateObj = new Date();
var val = dateObj.getTime();
//86400 * 1000 * 3 Each day is 86400 seconds
var days = 259200000;
val = val + days;
dateObj = new Date(val); // ********important*********//
val = dateObj.getMonth() + 1 + "/" + dateObj.getDate() + "/" + dateObj.getFullYear();
alert(val);
Try this:
var dateObj = new Date(Date.now() + 86400000 * 3);
Dates in JavaScript are accurate to the millisecond, so 1000
is 1 second.
There are 60 seconds in a minute, 60 minutes in an hour, and 24 hours in a day.
Therefore, one day is: 1000 * 60 * 60 * 24
, which is 86400000
milliseconds.
Date.now()
returns the current timestamp, accurate to the millisecond.
We pass that timestamp, with the added 3 days worth of milliseconds to new Date()
, which, when called with a number, creates a Date
object from the provided timestamp.
To add time, get the current date then add, as milliseconds, the specific amount of time, then create a new date with the value:
// 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);
To explain this further; the reason dataObj.setMilliseconds()
doesn't work is because it sets the dateobj's milliseconds PROPERTY to the specified value(a value between 0 and 999). It does not set, as milliseconds, the date of the object.
// 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
References:Date.now()
new Date()
Date.setMilliseconds()
If you need to make date computations in javascript, use moment.js:
moment().add(3, 'days').calendar();