Попытка добавить 3 дня в миллисекундах к текущей дате
var dateObj = new Date();
var val = dateObj.getTime();
//86400 * 1000 * 3 Each day is 86400 seconds
var days = 259200000;
val = val + days;
dateObj.setMilliseconds(val);
val = dateObj.getMonth() + 1 + "/" + dateObj.getDate() + "/" + dateObj.getFullYear();
alert(val);
Я пытаюсь взять текущую дату, добавить к ней три дня миллисекунды и показать дату на 3 дня позже. Например, если сегодня 10/09/2012, я бы хотел сказать 10/12/2012.
Но этот метод не работает... Я получаю месяцы и дни. Какие-либо предложения?
Ответы
Ответ 1
Чтобы добавить время, получите текущую дату, затем добавьте в миллисекундах определенное количество времени, затем создайте новую дату со значением:
// get the current date & time
var dateObj = 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
dateObj += 1000 * 60 * 60 * 24 * 3;
// create a new Date object, using the adjusted time
dateObj = new Date(dateObj);
Чтобы объяснить это дальше; причина dataObj.setMilliseconds()
не работает, потому что она устанавливает значение dateobj milliseconds PROPERTY указанному значению (значение от 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
Ответ 2
Попробуйте следующее:
var dateObj = new Date(Date.now() + 86400000 * 3);
Ответ 3
Если вам нужно сделать вычисления даты в javascript, используйте moment.js:
moment().add('days', 3).calendar();
Ответ 4
используйте этот код
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);