博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
为JavaScript日期添加天数
阅读量:3578 次
发布时间:2019-05-20

本文共 12709 字,大约阅读时间需要 42 分钟。

如何使用将天添加到当前Date 。 JavaScript是否具有诸如.Net的AddDay类的内置函数?


#1楼

尝试

var someDate = new Date();var duration = 2; //In DayssomeDate.setTime(someDate.getTime() +  (duration * 24 * 60 * 60 * 1000));

使用setDate()添加日期不会解决您的问题,请尝试在2月增加几天,如果尝试向其添加新日期,则不会达到预期的效果。


#2楼

感谢Jason的回答能按预期工作,这是您的代码和AnthonyWJones方便的格式的结合:

Date.prototype.addDays = function(days){    var ms = new Date().getTime() + (86400000 * days);    var added = new Date(ms);    return added;}

#3楼

setDate()的Mozilla文档未指示它将处理月末情况。 参见

设置日期()

  • 根据当地时间设置指定日期的月份(1-31)。

这就是为什么我需要添加天数时使用setTime()的原因。


#4楼

我的简单解决方案是:

nextday=new Date(oldDate.getFullYear(),oldDate.getMonth(),oldDate.getDate()+1);

此解决方案不存在夏令时的问题。 此外,您可以添加/扣除年份,月份,天数等的任何偏移量。

day=new Date(oldDate.getFullYear()-2,oldDate.getMonth()+22,oldDate.getDate()+61);

是正确的代码。


#5楼

遵循下面的示例,花了很长时间才试图弄清当年未达成的交易。

如果您只想简单地将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);

今天/明天的事情令人困惑。 通过将当前日期设置为新的日期变量,您会弄乱年份值。 如果您从原始日期开始工作,则不会。


#6楼

我昨晚创建了这些扩展:

您可以传递正值或负值;

例:

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;}

#7楼

正确答案

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;}

证明/示例

// Correct function addDays(date, days) { var result = new Date(date); result.setDate(result.getDate() + days); return result; } // Bad Year/Month function addDaysWRONG(date, days) { var result = new Date(); result.setDate(date.getDate() + days); return result; } // Bad during DST function addDaysDstFail(date, days) { var dayms = (days * 24 * 60 * 60 * 1000); return new Date(date.getTime() + dayms); } // TEST function formatDate(date) { return (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear(); } $('tbody tr td:first-child').each(function () { var $in = $(this); var $out = $('').insertAfter($in).addClass("answer"); var $outFail = $('').insertAfter($out); var $outDstFail = $('').insertAfter($outFail); var date = new Date($in.text()); var correctDate = formatDate(addDays(date, 1)); var failDate = formatDate(addDaysWRONG(date, 1)); var failDstDate = formatDate(addDaysDstFail(date, 1)); $out.text(correctDate); $outFail.text(failDate); $outDstFail.text(failDstDate); $outFail.addClass(correctDate == failDate ? "right" : "wrong"); $outDstFail.addClass(correctDate == failDstDate ? "right" : "wrong"); });
body { font-size: 14px; } table { border-collapse:collapse; } table, td, th { border:1px solid black; } td { padding: 2px; } .wrong { color: red; } .right { color: green; } .answer { font-weight: bold; }
 
DST Dates
Input +1 Day +1 Day Fail +1 Day DST Fail
03/10/2013
11/03/2013
03/09/2014
11/02/2014
03/08/2015
11/01/2015
2013
Input +1 Day +1 Day Fail +1 Day DST Fail
01/01/2013
02/01/2013
03/01/2013
04/01/2013
05/01/2013
06/01/2013
07/01/2013
08/01/2013
09/01/2013
10/01/2013
11/01/2013
12/01/2013
2014
Input +1 Day +1 Day Fail +1 Day DST Fail
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
11/01/2014
12/01/2014
2015
Input +1 Day +1 Day Fail +1 Day DST Fail
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


#8楼

如果可以,请使用 。 JavaScript没有很好的本机日期/时间方法。 以下是Moment语法的示例:

var nextWeek = moment().add(7, 'days'); alert(nextWeek);

参考: :


#9楼

//the_day is 2013-12-31    var the_day = Date.UTC(2013, 11, 31);     // Now, the_day will be "1388448000000" in UTC+8;     var the_next_day = new Date(the_day + 24 * 60 * 60 * 1000);    // Now, the_next_day will be "Wed Jan 01 2014 08:00:00 GMT+0800"

#10楼

我使用类似:

new Date(dateObject.getTime() + amountOfDays * 24 * 60 * 60 * 1000)

可以节省时间:

new Date(new Date(2014, 2, 29, 20, 0, 0).getTime() + 1 * 24 * 60 * 60 * 1000)

适用于新年:

new Date(new Date(2014, 11, 31, 20, 0, 0).getTime() + 1 * 24 * 60 * 60 * 1000)

可以参数化:

function DateAdd(source, amount, step) {  var factor = 1;  if (step == "day") factor = 24 * 60 * 60 * 1000;  else if (step == "hour") factor = 60 * 60 * 1000;  ...  new Date(source.getTime() + amount * factor);}

#11楼

晚会晚了,

但是如果您使用
jQuery那么
有个很棒的插件叫做Moment:

var myDateOfNowPlusThreeDays = moment().add(3, "days").toDate();

还有很多其他好东西!

编辑:jQuery参考删除由于aikeru的评论


#12楼

我想我也会给出答案:

就个人而言,我喜欢避免不必要的变量声明,方法调用和构造函数调用,因为它们在性能上都很昂贵。 (当然,在合理范围内)
我打算将其保留为@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。 这意味着,如果您添加了超过DST的天数,则显示的时间(小时)将发生变化以反映这一点。

例:
2014年11月2日02:00是DST的结束。

var dt = new Date( 2014, 10, 1, 10, 30, 0 );console.log( dt );                  // Sat Nov 01 2014 10:30:00console.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:00console.log( dt.addDays( 10 ) );    // Tue Nov 11 2014 10:30:00

#13楼

我知道老了,但有时候我喜欢这样:

function addDays(days) {    return new Date(Date.now() + 864e5 * days);}

#14楼

我正在使用以下解决方案。

var msInDay = 86400000;var daysToAdd = 5;var now = new Date();var milliseconds = now.getTime();var newMillisecods = milliseconds + msInDay * daysToAdd;var newDate = new Date(newMillisecods);//or now.setTime(newMillisecods);

Date具有一个接受int的构造函数。 此参数表示1970年1月1日之前/之后的总毫秒数。它也具有setTime方法,该方法无需创建新的Date对象即可执行此操作。

我们在这里所做的是将天数转换为毫秒,并将此值添加到getTime提供的值中。 最后,将结果提供给Date(milliseconds)构造函数或setTime(milliseconds)方法。


#15楼

编辑:代替setTime() (或setHours() ),您可以这样做:

Date.prototype.addDays= function(d){  this.setDate(this.getDate() + d);  return this;};var tomorrow = new Date().addDays(1);

旧:

除了使用setTime()还可以使用setHours()

Date.prototype.addDays= function(d){    this.setHours(this.getHours() + d * 24);    return this;};var tomorrow = new Date().addDays(1);

参见 ...


#16楼

对于使用Angular的用户:

做就是了:

$scope.booking.totTijd.setMinutes($scope.booking.totTijd.getMinutes()+15);$scope.booking.totTijd.setDate($scope.booking.totTijd.getDate() + 1);

#17楼

int days = 1;var newDate = new Date(Date.now() + days * 24*60*60*1000);

var days = 2; var newDate = new Date(Date.now() + days * 24*60*60*1000); document.write('Today: '); document.write(new Date()); document.write('
New: '); document.write(newDate);


#18楼

不,javascript没有内置函数,但是您可以使用简单的代码行

timeObject.setDate(timeObject.getDate() + countOfDays);

#19楼

最简单的解决方案。

Date.prototype.addDays = function(days) { this.setDate(this.getDate() + parseInt(days)); return this; }; // and then call var newDate = new Date().addDays(2); //+2 days console.log(newDate); // or var newDate1 = new Date().addDays(-2); //-2 days console.log(newDate1);


#20楼

非常简单的代码,可以在Java脚本中添加日期。

var d = new Date(); d.setDate(d.getDate() + prompt('how many days you want to add write here')); alert(d);


#21楼

提出的解决方案在夏令时方面存在问题。

通过使用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;}

#22楼

我们的团队认为是该领域中最好的图书馆。 它将日期视为不可变的 ( ),它速度更快,并且可以模块化加载。

const newDate = DateFns.addDays(oldDate, 2);

#23楼

有一个和方法,使您可以执行以下操作:

var newDate = aDate.setDate(aDate.getDate() + numberOfDays);

如果您要减去天数并以易于DateHelper格式设置日期格式,则应考虑创建一个自定义的DateHelper对象,该对象看起来像这样:

var DateHelper = { addDays : function(aDate, numberOfDays) { aDate.setDate(aDate.getDate() + numberOfDays); // Add numberOfDays return aDate; // Return the date }, format : function format(date) { return [ ("0" + date.getDate()).slice(-2), // Get day and pad it with zeroes ("0" + (date.getMonth()+1)).slice(-2), // Get month and pad it with zeroes date.getFullYear() // Get full year ].join('/'); // Glue the pieces together } } // With this helper, you can now just use one line of readable code to : // --------------------------------------------------------------------- // 1. Get the current date // 2. Add 20 days // 3. Format it // 4. Output it // --------------------------------------------------------------------- document.body.innerHTML = DateHelper.format(DateHelper.addDays(new Date(), 20));

(另请参阅 )


#24楼

您可以使用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;

#25楼

没有变量的通用原型,它适用于现有的Date值:

Date.prototype.addDays = function (days) {    return new Date(this.valueOf() + days * 864e5);}

#26楼

无需使用第二个变量,您可以将x替换为接下来的x天:

let d=new Date(new Date().getTime() + (7 * 24 * 60 * 60 * 1000));

#27楼

减去30天使用时间(24h = 86400000ms)

new Date(+yourDate - 30 *86400000)

var yourDate=new Date(); var d = new Date(+yourDate - 30 *86400000) console.log(d)


#28楼

var today = new Date();var tomorrow = new Date();tomorrow.setDate(today.getDate()+1);

注意,因为这可能很棘手。 设置“明天”时,它仅起作用,因为它的当前值与“今天”的年份和月份相匹配。 但是,将日期数字设置为“ 32”通常仍可以将其移至下个月。


#29楼

您可以使用以下方法创建一个:

Date.prototype.addDays = function(days) { var date = new Date(this.valueOf()); date.setDate(date.getDate() + days); return date; } var date = new Date(); alert(date.addDays(5));

这样可以在必要时自动增加月份。 例如:

8/31 + 1天将变为9/1

直接使用setDate的问题在于它是一个mutator,最好避免这种事情。 ECMA认为将Date视为可变类而不是不变结构是合适的。


#30楼

就这么简单:

new Date((new Date()).getTime() + (60*60*24*1000));

#31楼

这些答案让我感到困惑,我更喜欢:

var ms = new Date().getTime() + 86400000;var tomorrow = new Date(ms);

getTime()自1970年以来为我们提供毫秒,并且86400000是一天中的毫秒数。 因此,ms包含所需日期的毫秒数。

使用毫秒构造函数可提供所需的日期对象。

转载地址:http://faogj.baihongyu.com/

你可能感兴趣的文章
项目整合微信扫码登录功能
查看>>
分布式文件系统FastDfs的搭建
查看>>
Springboot项目利用Java客户端调用FastDFS
查看>>
全文检索工具elasticsearch的安装和简单介绍
查看>>
利用Kibana学习全文检索工具elasticsearch
查看>>
SpringBoot在Test测试类或自定义类中通过@Autowired注入为null
查看>>
使用docker搭建YAPI服务
查看>>
西南科技大学OJ题 邻接表到邻接矩阵1056
查看>>
西南科技大学OJ题 有向图的出度计算1057
查看>>
西南科技大学OJ题 有向图的最大出度计算1059
查看>>
西南科技大学OJ题 带权有向图计算1063
查看>>
oracle主键自增触发器编写
查看>>
String与StringBuilder与StringBuffer三者的差别
查看>>
各种IO流之间的关系和区别
查看>>
SSM如何实现上传单图片
查看>>
SSM环境下java如何实现语音识别(百度语音识别版)
查看>>
ajax方法参数的用法和他的含义
查看>>
数据库基础技巧及用法
查看>>
实用方法:无request参数时获得当前的request的方法
查看>>
JS操作数组常用实用方法
查看>>