Javascript 正在尝试将3天(以毫秒为单位)添加到当前日期
我正在尝试获取当前日期,在其中添加三天的毫秒,并使日期戳显示在距当前日期3天后。例如,如果今天是2012年9月10日,那么我希望它是2012年12月10日Javascript 正在尝试将3天(以毫秒为单位)添加到当前日期,javascript,date,Javascript,Date,我正在尝试获取当前日期,在其中添加三天的毫秒,并使日期戳显示在距当前日期3天后。例如,如果今天是2012年9月10日,那么我希望它是2012年12月10日 这种方法不起作用,我已经过了好几个月好几天了。有什么建议吗?如果需要使用javascript进行日期计算,请使用: 要添加时间,请获取当前日期,然后以毫秒为单位添加特定的时间量,然后使用以下值创建新日期: moment().add(3, 'days').calendar(); 进一步解释这一点;之所以dataObj.setmillizes(
这种方法不起作用,我已经过了好几个月好几天了。有什么建议吗?如果需要使用javascript进行日期计算,请使用:
要添加时间,请获取当前日期,然后以毫秒为单位添加特定的时间量,然后使用以下值创建新日期:
moment().add(3, 'days').calendar();
进一步解释这一点;之所以dataObj.setmillizes()
不起作用,是因为它将dateobj的millizes属性设置为指定的值(介于0和999之间的值)。它不会将对象的日期设置为毫秒
// 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);
试试这个:
var dateObj=新日期(Date.now()+86400000*3);
JavaScript中的日期精确到毫秒,因此1000
为1秒。一分钟有60秒,一小时有60分钟,一天有24小时 因此,一天是:
1000*60*60*24
,即86400000
毫秒
Date.now()
返回当前时间戳,精确到毫秒。我们传递该时间戳,并向
new Date()
添加3天的毫秒,当使用数字调用时,它将根据提供的时间戳创建一个日期
对象。使用此代码
// 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
如果要对更任意的
日期对象(而不是.now()
)执行此操作,可以使用以下方法:
const initialDate=新日期(“2021年3月20日19:00”);
常数毫秒相加=30*24*60*60*1000//30天(毫秒)
const expiryDate=新日期(initialDate.valueOf()+毫秒添加);
我认为您需要的是设置时间而不是设置毫秒。stry:dateObj.setTime(dateObj.getTime()+8.64e7*3)
但请注意,夏令时转换可能会产生意外的结果。只需在日期中添加3就更简单了:dateObj.setDate(dateObj.getDate()+3)
。无意冒犯您,但建议使用整个库来完成这样一项简单的任务似乎太过分了。无意冒犯,当其他人阅读我的代码时,他可能会比公认的答案更好地理解moment.js一行。没有任何事情“简单”关于这个任务。考虑夏时制的时间变化。进一步阅读:我只是var天=259200000,因为它是静态的,而且永远不会改变。谢谢!好奇,为什么没有毫秒(天)做同样的事?我不知道。我只知道从经验,如果它是静态值,然后做计算出如上。(一年后)将毫秒添加到日期中的第一项,SetMillicles不起作用的原因是它设置了日期对象的毫秒部分。因此,在正常操作中,它需要0-999之间的数字。但是,它允许任何数字,就像将值添加到日期中,而不包含日期的前一个毫秒组件。它将毫秒表示为1000*60*60*24*3将更清晰。此答案不考虑夏令时。如果指定初始日期:var dateObject=new date('2019年11月2日'),再加上3天,将得到跨越DST的2019年11月4日(含11月4日)。但如果从var dateObj=new date('2019年11月4日')开始;您将获得2019年11月7日,包括4天。您知道如何计算DST吗?
// 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
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);