Javascript 尝试将 3 天(以毫秒为单位)添加到当前日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12795767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Trying to add 3 days in Milliseconds to current Date
提问by dman
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);
I am trying to take the current date, add three days of milliseconds to it, and have the date stamp show 3 days later from the current. For example - if today is 10/09/2012 then I would like it to say 10/12/2012.
我正在尝试获取当前日期,为其添加三天的毫秒数,并在当前日期后 3 天显示日期戳。例如 - 如果今天是 10/09/2012 那么我想说 10/12/2012。
this method is not working, I am getting the months and days way off. Any suggestions?
这种方法行不通,我已经过了几个月和几天的时间。有什么建议?
回答by SReject
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
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);
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.
进一步解释这一点;原因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
回答by MiniGod
Try this:
尝试这个:
var dateObj = new Date(Date.now() + 86400000 * 3);
var dateObj = new Date(Date.now() + 86400000 * 3);
回答by Nicolas Modrzyk
回答by Kasma
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);