如何使用 JavaScript 为当前 Date
添加天数? JavaScript 是否有像 .NET 的 AddDay()
这样的内置函数?
您可以使用以下方法创建一个:-
Date.prototype.addDays = function(days) { var date = new Date(this.valueOf()); date.setDate(date.getDate() + days);归期; } 变种日期 = 新日期(); console.log(date.addDays(5));
如果需要,这会自动增加月份。例如:
8/31 + 1 天将变为 9/1。
直接使用 setDate
的问题在于它是一个 mutator,最好避免这种事情。 ECMA 认为将 Date
视为可变类而不是不可变结构是合适的。
正确答案:
function addDays(date, days) {
var result = new Date(date);
result.setDate(result.getDate() + days);
return result;
}
错误的答案:
这个答案有时会提供正确的结果,但通常会返回错误的年份和月份。此答案唯一有效的时间是您添加天数的日期恰好是当前年份和月份。
// Don't do it this way!
function addDaysWRONG(date, days) {
var result = new Date();
result.setDate(date.getDate() + days);
return result;
}
证明/例子
// 正确 function addDays(date, days) { var result = new Date(date); result.setDate(result.getDate() + days);返回结果; } // 坏年/月 function addDaysWRONG(date, days) { var result = new Date(); result.setDate(date.getDate() + days);返回结果; } // 夏令时期间出错 function addDaysDstFail(date, days) { var dayms = (days * 24 * 60 * 60 * 1000);返回新日期(日期.getTime()+天); } // 测试函数 formatDate(date) { return (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear(); } $('tbody tr td:first-child').each(function () { var $in = $(this); var $out = $('
夏令时日期 | |||
---|---|---|---|
输入 | +1天 | +1天失败 | + 1 天 DST 失败 |
03/10/2013 | |||
11/03/2013 | |||
03/09/2014 | |||
11/02/2014 | |||
03/08/2015< /td> | |||
11/01/2015 | |||
2013 | |||
+1 天 | +1 天失败 | +1 天夏令时失败 | |
01/01/2013 | |||
02/01/2013 | |||
03/01/2013 | |||
04/01/2013 | |||
05/01/2013 | |||
06/01/2013 | |||
07/01/2013 | |||
08/01/2013 | |||
10/01/2013 | |||
11/01/2013 | < /tr>|||
12/01/2013 | |||
2014 | |||
输入< /th> | +1 天 | +1 天失败 | +1 天 DST 失败 | th>
01/01/2014 | |||
02/01/2014 | |||
03/01/2014 | |||
04/01/2014 | |||
05/01/2014 | |||
06/01/2014 | |||
07/01/2014 | |||
08/01/2014 | |||
09/01/2014 | |||
10/01/2014 | |||
12/01/2014 | |||
2015 | |||
输入 | +1天 | +1天失败 | +1天夏令时失败 | tr>
01/01/2015 | |||
02/01/2015 | |||
03/01/ 2015 | |||
04/01/2015 | |||
05/01/2015 | |||
06/01/2015 | |||
07/01/2015 | |||
08/01/2015 | |||
09/01/2015 | |||
10/01/2015 | |||
11/ 01/2015 | |||
12/01/2015 |
new Date(date.getTime());
更好,但我认为 new Date(date)
不会因为字符串转换而给出错误答案。如果有人可以提供一个例子,我想看看。如果日期构造函数不以默认格式读取字符串,那该有多疯狂。据我了解,用户的本地时区和日期格式设置应该不会影响此功能的正确性。
new Date();
与 new Date(date)
。第一个使用当前年、月和日创建;然后改变一天。第二个使用 given 年、月、日创建日期,然后更改日期。
var today = new Date();
var tomorrow = new Date();
tomorrow.setDate(today.getDate()+1);
要小心,因为这可能很棘手。设置 tomorrow
时,它之所以有效,是因为它的当前值与 today
的年份和月份相匹配。但是,设置为像“32”这样的日期数字通常仍然可以很好地将其移至下个月。
var d = new Date(); d.setDate( d.getDate() + 1 );
?
getDate()
将返回 那一年的某天。然后,调用 setDate
将日期设置为 当前年份。所以它不是一个很好的通用解决方案。 @AnthonyWJones's answer 实际上工作正常。
var d = new Date(2015,11,30);d.setDate(d.getDate() + 370)
给出了 2017 年 1 月 3 日,它跨越了 2 年。
我的简单解决方案是:
nextday=new Date(oldDate.getFullYear(),oldDate.getMonth(),oldDate.getDate()+1);
此解决方案没有夏令时问题。此外,您可以添加/减少年、月、日等的任何偏移量。
day=new Date(oldDate.getFullYear()-2,oldDate.getMonth()+22,oldDate.getDate()+61);
是正确的代码。
setDate
,所以我们刚刚遇到了夏令时问题。
这些答案让我感到困惑,我更喜欢:
var ms = new Date().getTime() + 86400000;
var tomorrow = new Date(ms);
getTime() 为我们提供自 1970 年以来的毫秒数,而 86400000 是一天中的毫秒数。因此, ms 包含所需日期的毫秒数。
使用毫秒构造函数给出所需的日期对象。
new Date(new Date('11/4/2012').getTime() + 86400000)
这是用于在 Javascript 中为特定日期添加日、月和年的方法。
// To add Days
var d = new Date();
d.setDate(d.getDate() + 5);
// To add Months
var m = new Date();
m.setMonth(m.getMonth() + 5);
// To add Years
var y = new Date();
y.setFullYear(y.getFullYear() + 5);
尝试
var someDate = new Date();
var duration = 2; //In Days
someDate.setTime(someDate.getTime() + (duration * 24 * 60 * 60 * 1000));
使用 setDate() 添加日期不会解决您的问题,请尝试在 2 月添加一些天数,如果您尝试向其中添加新天数,则不会达到您的预期。
setDate()
的“二月”问题的任何证据吗?是这样吗:stackoverflow.com/questions/5497637/…
在遵循下面的主要示例时,只是花了很长时间试图弄清楚一年没有添加的交易是什么。
如果您只想简单地将 n 天添加到您拥有的日期,您最好只是去:
myDate.setDate(myDate.getDate() + n);
或冗长的版本
var theDate = new Date(2013, 11, 15);
var myNewDate = new Date(theDate);
myNewDate.setDate(myNewDate.getDate() + 30);
console.log(myNewDate);
今天/明天的事情令人困惑。通过将当前日期设置为新的日期变量,您将弄乱年份值。如果您从原始日期开始工作,则不会。
我实现的最简单的方法是使用 Date() 本身。 `
const days = 15;
// Date.now() gives the epoch date value (in milliseconds) of current date
nextDate = new Date( Date.now() + days * 24 * 60 * 60 * 1000)
`
int days = 1;
var newDate = new Date(Date.now() + days * 24*60*60*1000);
变天 = 2; var newDate = new Date(Date.now() + days * 24*60*60*1000); document.write('今天:'); document.write(new Date()); document.write('
新:'); document.write(newDate);
如果可以,请使用 moment.js。 JavaScript 没有很好的原生日期/时间方法。以下是 Moment 的语法示例:
var nextWeek = moment().add(7, 'days');警报(下周);
参考:http://momentjs.com/docs/#/manipulating/add/
我昨晚创建了这些扩展:您可以传递正值或负值;
例子:
var someDate = new Date();
var expirationDate = someDate.addDays(10);
var previous = someDate.addDays(-5);
Date.prototype.addDays = function (num) {
var value = this.valueOf();
value += 86400000 * num;
return new Date(value);
}
Date.prototype.addSeconds = function (num) {
var value = this.valueOf();
value += 1000 * num;
return new Date(value);
}
Date.prototype.addMinutes = function (num) {
var value = this.valueOf();
value += 60000 * num;
return new Date(value);
}
Date.prototype.addHours = function (num) {
var value = this.valueOf();
value += 3600000 * num;
return new Date(value);
}
Date.prototype.addMonths = function (num) {
var value = new Date(this.valueOf());
var mo = this.getMonth();
var yr = this.getYear();
mo = (mo + num) % 12;
if (0 > mo) {
yr += (this.getMonth() + num - mo - 12) / 12;
mo += 12;
}
else
yr += ((this.getMonth() + num - mo) / 12);
value.setMonth(mo);
value.setYear(yr);
return value;
}
为 pipeline operator 设计的解决方案:
const addDays = days => date => {
const result = new Date(date);
result.setDate(result.getDate() + days);
return result;
};
用法:
// Without the pipeline operator...
addDays(7)(new Date());
// And with the pipeline operator...
new Date() |> addDays(7);
如果您需要更多功能,我建议您查看 date-fns 库。
最简单的答案是,假设需要在当前日期上增加 1 天:
var currentDate = new Date();
var numberOfDayToAdd = 1;
currentDate.setDate(currentDate.getDate() + numberOfDayToAdd );
逐行向您解释这段代码的作用:
创建名为 currentDate 的当前日期变量。默认情况下,“new Date()”会自动将当前日期分配给变量。创建一个变量来保存要添加到日期的天数(可以跳过这个变量,直接使用第三行中的值) 更改 Date 的值(因为 Date 是保存在对象)通过给出相同的值 + 你想要的数字。自动切换到下个月
在不使用第二个变量的情况下,您可以将 7 替换为接下来的 x 天:
let d=new Date(new Date().getTime() + (7 * 24 * 60 * 60 * 1000));
减去 30 天使用 (24h=86400000ms)
new Date(+yourDate - 30 *86400000)
var yourDate=new Date(); var d = new Date(+yourDate - 30 *86400000) console.log(d)
最简单的解决方案。
Date.prototype.addDays = function(days) { this.setDate(this.getDate() + parseInt(days));返回这个; }; // 然后调用 var newDate = new Date().addDays(2); //+2 天 console.log(newDate); // 或 var newDate1 = new Date().addDays(-2); //-2 天 console.log(newDate1);
迟到了,但是如果你使用 有一个很棒的插件叫做 Moment:
jQuery
那么
var myDateOfNowPlusThreeDays = moment().add(3, "days").toDate();
http://momentjs.com/docs/#/manipulating/
还有很多其他的好东西!
编辑:由于 aikeru 的评论删除了 jQuery 参考
您可以使用 JavaScript,不需要 jQuery:
var someDate = new Date();
var numberOfDaysToAdd = 6;
someDate.setDate(someDate.getDate() + numberOfDaysToAdd);
Formatting to dd/mm/yyyy :
var dd = someDate.getDate();
var mm = someDate.getMonth() + 1;
var y = someDate.getFullYear();
var someFormattedDate = dd + '/'+ mm + '/'+ y;
就这么简单:
new Date((new Date()).getTime() + (60*60*24*1000));
感谢 Jason 您的回答按预期工作,这是您的代码和 AnthonyWJones 的方便格式的混合:
Date.prototype.addDays = function(days){
var ms = new Date().getTime() + (86400000 * days);
var added = new Date(ms);
return added;
}
老我知道,但有时我喜欢这样:
function addDays(days) {
return new Date(Date.now() + 864e5 * days);
}
Date.prototype.addDays = function(days) {return new Date(this.getTime() + (864e5 * days));};
你可以试试:
var days = 50;
const d = new Date();
d.setDate(d.getDate() + days)
这应该运作良好。
不,javascript没有内置函数,但你可以使用简单的代码行
timeObject.setDate(timeObject.getDate() + countOfDays);
我在建议的解决方案中遇到了夏令时问题。
通过改用 getUTCDate
/ setUTCDate
,我解决了我的问题。
// Curried, so that I can create helper functions like `add1Day`
const addDays = num => date => {
// Make a working copy so we don't mutate the supplied date.
const d = new Date(date);
d.setUTCDate(d.getUTCDate() + num);
return d;
}
为什么这么复杂?
假设您将要添加的天数存储在名为 days_to_add 的变量中。
那么这个简短的应该做到这一点:
calc_date = new Date(Date.now() +(days_to_add * 86400000));
使用 Date.now() 您可以获得实际的 unix 时间戳,以毫秒为单位,然后添加任意多的毫秒数,以添加天数。一天是 24h60min60s*1000ms = 86400000 ms 或 864E5。
没有变量的通用原型,它适用于现有的 Date 值:
Date.prototype.addDays = function (days) {
return new Date(this.valueOf() + days * 864e5);
}
setDate() 的 mozilla 文档并未表明它将处理月末方案。请参阅https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date
设置日期()
根据本地时间设置指定日期的月份日期 (1-31)。
这就是我需要添加天数时使用 setTime() 的原因。
我想我也会给出一个答案:就个人而言,我喜欢尝试避免无缘无故的变量声明、方法调用和构造函数调用,因为它们在性能上都很昂贵。 (当然,在合理范围内)我打算在@AnthonyWJones 给出的答案下发表评论,但想得更好。
// Prototype usage...
Date.prototype.addDays = Date.prototype.addDays || function( days ) {
return this.setTime( 864E5 * days + this.valueOf() ) && this;
};
// Namespace usage...
namespace.addDaysToDate = function( date, days ) {
return date.setTime( 864E5 * days + date.valueOf() ) && date;
};
// Basic Function declaration...
function addDaysToDate( date, days ) {
return date.setTime( 864E5 * days + date.valueOf() ) && date;
};
以上将尊重夏令时。这意味着如果您添加跨 DST 的天数,则显示的时间(小时)将改变以反映这一点。示例:2014 年 11 月 2 日 02:00 是夏令时结束。
var dt = new Date( 2014, 10, 1, 10, 30, 0 );
console.log( dt ); // Sat Nov 01 2014 10:30:00
console.log( dt.addDays( 10 ) ); // Tue Nov 11 2014 09:30:00
如果您希望保留整个 DST 的时间(所以 10:30 仍然是 10:30)...
// Prototype usage...
Date.prototype.addDays = Date.prototype.addDays || function( days ) {
return this.setDate( this.getDate() + days ) && this;
};
// Namespace usage...
namespace.addDaysToDate = function( date, days ) {
return date.setDate( date.getDate() + days ) && date;
};
// Basic Function declaration...
function addDaysToDate( date, days ) {
return date.setDate( date.getDate() + days ) && date;
};
所以,现在你有...
var dt = new Date( 2014, 10, 1, 10, 30, 0 );
console.log( dt ); // Sat Nov 01 2014 10:30:00
console.log( dt.addDays( 10 ) ); // Tue Nov 11 2014 10:30:00
短的:
function addDays(date, number) {
const newDate = new Date(date);
return new Date(newDate.setDate(newDate.getDate() + number));
}
console.log({
tomorrow: addDays(new Date(), 1)
});
进步:
function addDays(date, number) {
const newDate = new Date(date);
return new Date(newDate.setDate(date.getDate() + number));
}
function addMonths(date, number) {
const newDate = new Date(date);
return new Date(newDate.setMonth(newDate.getMonth() + number));
}
function addYears(date, number) {
const newDate = new Date(date);
return new Date(newDate.setFullYear(newDate.getFullYear() + number));
}
function getNewDate(dateTime) {
let date = new Date();
let number = parseInt(dateTime.match(/\d+/)[0]);
if (dateTime.indexOf('-') != -1)
number = (- number);
if (dateTime.indexOf('day') != -1)
date = addDays(date, number);
else if (dateTime.indexOf('month') != -1)
date = addMonths(date, number);
else if (dateTime.indexOf('year') != -1)
date = addYears(date, number);
return date;
}
console.log({
tomorrow: getNewDate('+1day'),
yesterday: getNewDate('-1day'),
nextMonth: getNewDate('+1month'),
nextYear: getNewDate('+1year'),
});
由 jperl 提供修复
addDays(today, 1)
,今天就是明天。 function addDays(date, number) { const newDate = new Date(date) return new Date(newDate.setDate(newDate.getDate() + number)); }
Date.prototype.addDays=function(d){return new Date(this.valueOf()+864E5*d);};
864E5
出于某种原因,我更喜欢在我的代码中编写24*60*60
:)