简体   繁体   English

如何将日期添加到日期?

[英]How to add days to Date?

How to add days to current Date using JavaScript?如何使用 JavaScript 将天数添加到当前Date Does JavaScript have a built in function like .NET's AddDay() ? JavaScript 是否像 .NET 的AddDay()一样内置 function ?

You can create one with:-您可以使用以下方法创建一个:-

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

This takes care of automatically incrementing the month if necessary.如有必要,这会自动增加月份。 For example:例如:

8/31 + 1 day will become 9/1 . 8/31 + 1 天将变成9/1

The problem with using setDate directly is that it's a mutator and that sort of thing is best avoided.直接使用setDate的问题在于它是一个 mutator,最好避免这种事情。 ECMA saw fit to treat Date as a mutable class rather than an immutable structure. ECMA 认为适合将Date视为可变类而不是不可变结构。

Correct Answer :正确答案

function addDays(date, days) {
  var result = new Date(date);
  result.setDate(result.getDate() + days);
  return result;
}

Incorrect Answer :错误答案

This answer sometimes provides the correct result but very often returns the wrong year and month.此答案有时会提供正确的结果,但通常会返回错误的年份和月份。 The only time this answer works is when the date that you are adding days to happens to have the current year and month.此答案唯一有效的时间是您添加天数的日期恰好是当前年份和月份。

// Don't do it this way!
function addDaysWRONG(date, days) {
  var result = new Date();
  result.setDate(date.getDate() + days);
  return result;
}

Proof / Example证明/例子

Check this JsFiddle检查这个 JsFiddle

 // 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 = $('<td/>').insertAfter($in).addClass("answer"); var $outFail = $('<td/>').insertAfter($out); var $outDstFail = $('<td/>').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; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <table> <tbody> <tr> <th colspan="4">DST Dates</th> </tr> <tr> <th>Input</th> <th>+1 Day</th> <th>+1 Day Fail</th> <th>+1 Day DST Fail</th> </tr> <tr><td>03/10/2013</td></tr> <tr><td>11/03/2013</td></tr> <tr><td>03/09/2014</td></tr> <tr><td>11/02/2014</td></tr> <tr><td>03/08/2015</td></tr> <tr><td>11/01/2015</td></tr> <tr> <th colspan="4">2013</th> </tr> <tr> <th>Input</th> <th>+1 Day</th> <th>+1 Day Fail</th> <th>+1 Day DST Fail</th> </tr> <tr><td>01/01/2013</td></tr> <tr><td>02/01/2013</td></tr> <tr><td>03/01/2013</td></tr> <tr><td>04/01/2013</td></tr> <tr><td>05/01/2013</td></tr> <tr><td>06/01/2013</td></tr> <tr><td>07/01/2013</td></tr> <tr><td>08/01/2013</td></tr> <tr><td>09/01/2013</td></tr> <tr><td>10/01/2013</td></tr> <tr><td>11/01/2013</td></tr> <tr><td>12/01/2013</td></tr> <tr> <th colspan="4">2014</th> </tr> <tr> <th>Input</th> <th>+1 Day</th> <th>+1 Day Fail</th> <th>+1 Day DST Fail</th> </tr> <tr><td>01/01/2014</td></tr> <tr><td>02/01/2014</td></tr> <tr><td>03/01/2014</td></tr> <tr><td>04/01/2014</td></tr> <tr><td>05/01/2014</td></tr> <tr><td>06/01/2014</td></tr> <tr><td>07/01/2014</td></tr> <tr><td>08/01/2014</td></tr> <tr><td>09/01/2014</td></tr> <tr><td>10/01/2014</td></tr> <tr><td>11/01/2014</td></tr> <tr><td>12/01/2014</td></tr> <tr> <th colspan="4">2015</th> </tr> <tr> <th>Input</th> <th>+1 Day</th> <th>+1 Day Fail</th> <th>+1 Day DST Fail</th> </tr> <tr><td>01/01/2015</td></tr> <tr><td>02/01/2015</td></tr> <tr><td>03/01/2015</td></tr> <tr><td>04/01/2015</td></tr> <tr><td>05/01/2015</td></tr> <tr><td>06/01/2015</td></tr> <tr><td>07/01/2015</td></tr> <tr><td>08/01/2015</td></tr> <tr><td>09/01/2015</td></tr> <tr><td>10/01/2015</td></tr> <tr><td>11/01/2015</td></tr> <tr><td>12/01/2015</td></tr> </tbody> </table>

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

Be careful, because this can be tricky.小心,因为这可能很棘手。 When setting tomorrow , it only works because its current value matches the year and month for today .设置tomorrow ,它仅起作用,因为它的当前值与today的年和月匹配。 However, setting to a date number like "32" normally will still work just fine to move it to the next month.但是,设置为“32”之类的日期数字通常仍然可以正常工作以将其移至下个月。

My simple solution is:我的简单解决方案是:

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

this solution does not have problem with daylight saving time.此解决方案没有夏令时问题。 Also, one can add/sub any offset for years, months, days etc.此外,您可以添加/减少年、月、日等的任何偏移量。

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

is correct code.是正确的代码。

These answers seem confusing to me, I prefer:这些答案让我感到困惑,我更喜欢:

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

getTime() gives us milliseconds since 1970, and 86400000 is the number of milliseconds in a day. getTime() 为我们提供自 1970 年以来的毫秒数,86400000 是一天中的毫秒数。 Hence, ms contains milliseconds for the desired date.因此, ms 包含所需日期的毫秒数。

Using the millisecond constructor gives the desired date object.使用毫秒构造函数提供所需的日期对象。

Try尝试

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

Using setDate() to add a date wont solve your problem, try adding some days to a Feb month, if you try to add new days to it, it wont result in what you expected.使用 setDate() 添加日期无法解决您的问题,请尝试在 2 月的月份中添加一些天数,如果您尝试向其中添加新的天数,则不会达到您的预期。

Just spent ages trying to work out what the deal was with the year not adding when following the lead examples below.只是花了很长时间试图找出在遵循以下主要示例时未添加年份的交易。

If you want to just simply add n days to the date you have you are best to just go:如果您只想简单地将 n 天添加到您拥有的日期,那么您最好去:

myDate.setDate(myDate.getDate() + n); myDate.setDate(myDate.getDate() + n);

or the longwinded version或冗长的版本

var theDate = new Date(2013, 11, 15);
var myNewDate = new Date(theDate);
myNewDate.setDate(myNewDate.getDate() + 30);
console.log(myNewDate);

This today/tomorrow stuff is confusing.今天/明天的事情令人困惑。 By setting the current date into your new date variable you will mess up the year value.通过将当前日期设置为您的新日期变量,您将弄乱年份值。 if you work from the original date you won't.如果您从原始日期开始工作,则不会。

Here is the way that use to add days, months, and years for a particular date in Javascript.这是用于在 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 m = new Date();
m.setFullYear(m.getFullYear() + 5);
int days = 1;
var newDate = new Date(Date.now() + days * 24*60*60*1000);

CodePen代码笔

 var days = 2; var newDate = new Date(Date.now() + days * 24*60*60*1000); document.write('Today: <em>'); document.write(new Date()); document.write('</em><br/> New: <strong>'); document.write(newDate);

The simplest approach that I have implemented is to use Date() itself.我实施的最简单的方法是使用 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)

` `

If you can, use moment.js .如果可以,请使用moment.js JavaScript doesn't have very good native date/time methods. JavaScript 没有很好的原生日期/时间方法。 The following is an example Moment's syntax:下面是一个示例 Moment 的语法:

 var nextWeek = moment().add(7, 'days'); alert(nextWeek);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment-with-locales.min.js"></script>

Reference: http://momentjs.com/docs/#/manipulating/add/参考: http : //momentjs.com/docs/#/manipulating/add/

I created these extensions last night:我昨晚创建了这些扩展:
you can pass either positive or negative values;您可以传递正值或负值;

example:例子:

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

the simplest answer is, assuming the need is to add 1 day to the current date:最简单的答案是,假设需要将 1 天添加到当前日期:

var currentDate = new Date();
var numberOfDayToAdd = 1;
currentDate.setDate(currentDate.getDate() + numberOfDayToAdd );

To explain to you, line by line, what this code does:逐行向您解释此代码的作用:

  1. Create the current date variable named currentDate.创建名为 currentDate 的当前日期变量。 By default "new Date()" automatically assigns the current date to the variable.默认情况下,“new Date()”会自动将当前日期分配给变量。
  2. Create a variable to save the number of day(s) to add to the date (you can skip this variable and use directly the value in the third line)创建一个变量来保存要添加到日期的天数(您可以跳过此变量并直接使用第三行中的值)
  3. Change the value of Date (because Date is the number of the month's day saved in the object) by giving the same value + the number you want.通过提供相同的值 + 您想要的数字来更改Date的值(因为 Date 是保存在对象中的月份的天数)。 The switch to the next month will be automatic自动切换到下个月

A solution designed for the pipeline operator :管道运营商设计的解决方案:

const addDays = days => date => {
  const result = new Date(date);

  result.setDate(result.getDate() + days);

  return result;
};

Usage:用法:

// Without the pipeline operator...
addDays(7)(new Date());

// And with the pipeline operator...
new Date() |> addDays(7);

If you need more functionality, I suggest looking into the date-fns library.如果您需要更多功能,我建议您查看date-fns库。

不使用第二个变量,您可以用接下来的 x 天替换 7:

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

to substract 30 days use (24h=86400000ms)减去30天的使用时间(24h=86400000ms)

new Date(+yourDate - 30 *86400000)

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

The simplest solution.最简单的解决方案。

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

Late to the party, but if you use jQuery then there's an excellent plugin called Moment:迟到了, 但如果你使用 jQuery那么 有一个名为 Moment 的优秀插件:

http://momentjs.com/ http://momentjs.com/

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

http://momentjs.com/docs/#/manipulating/ http://momentjs.com/docs/#/manipulating/

And lots of other good stuff in there!还有很多其他的好东西!

Edit: jQuery reference removed thanks to aikeru's comment编辑:由于 aikeru 的评论,jQuery 参考被删除

You can use JavaScript, no jQuery required:您可以使用 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));

Thanks Jason for your answer that works as expected, here is a mix from your code and the handy format of AnthonyWJones :感谢 Jason 的回答按预期工作,这是您的代码和 AnthonyWJones 的方便格式的混合:

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

Old I know, but sometimes I like this:老我知道,但有时我喜欢这样:

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

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

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

I had issues with daylight savings time with the proposed solution.我在建议的解决方案中遇到了夏令时问题。

By using getUTCDate / setUTCDate instead, I solved my issue.通过使用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;
}

Why so complicated?为什么这么复杂?

Let's assume you store the number of days to add in a variable called days_to_add.假设您将要添加的天数存储在名为 days_to_add 的变量中。

Then this short one should do it:那么这个简短的应该这样做:

calc_date = new Date(Date.now() +(days_to_add * 86400000));

With Date.now() you get the actual unix timestamp as milliseconds and then you add as many milliseconds as you want to add days to.使用 Date.now() 可以获得以毫秒为单位的实际 unix 时间戳,然后添加尽可能多的毫秒数,以添加天数。 One day is 24h 60min 60s*1000ms = 86400000 ms or 864E5.一天是 24h 60min 60s*1000ms = 86400000 ms 或 864E5。

Generic prototype with no variables, it applies on an existing Date value:没有变量的通用原型,它适用于现有的日期值:

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

The mozilla docs for setDate() don't indicate that it will handle end of month scenarios. setDate() 的 mozilla 文档并未表明它将处理月末情况。 See https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date请参阅https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date

setDate()设置日期()

  • Sets the day of the month (1-31) for a specified date according to local time.根据本地时间为指定日期设置月中的第几天 (1-31)。

That is why I use setTime() when I need to add days.这就是为什么我在需要添加天数时使用 setTime() 的原因。

I guess I'll give an answer as well:我想我也会给出一个答案:
Personally, I like to attempt to avoid gratuitous variable declaration, method calls, and constructor calls, as they are all expensive on performance.就我个人而言,我喜欢尝试避免无缘无故的变量声明、方法调用和构造函数调用,因为它们在性能上都是昂贵的。 (within reason, of course) (当然,在合理范围内)
I was going to leave this as just comment under the Answer given by @AnthonyWJones but thought better of it.我打算把它作为@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;
};

The above will respect DST.以上将尊重夏令时。 Meaning if you add a number of days that cross DST, the displayed time (hour) will change to reflect that.这意味着如果您添加跨越 DST 的天数,显示的时间(小时)将更改以反映这一点。
Example:例子:
Nov 2, 2014 02:00 was the end of 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

If you're looking to retain the time across DST (so 10:30 will still be 10:30)...如果您希望保留整个 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;
};

So, now you have...所以,现在你有...

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

I use something like:我使用类似的东西:

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

Works with day saving time:与天节省时间一起使用:

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

Works with new year:与新年一起工作:

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

It can be parametrized:它可以被参数化:

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

Edit: Instead of setTime() (or setHours() ) you could do it this way:编辑:您可以这样做,而不是setTime() (或setHours() ):

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

var tomorrow = new Date().addDays(1);

Old:老的:

Instead of using setTime() you can use setHours() :您可以使用setHours()代替使用setTime() setHours()

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

var tomorrow = new Date().addDays(1);

See the JSFiddle ...JSFiddle ...

Extending prototype in javascript may not be a good idea , especially in professional codebases.在 javascript 中扩展原型可能不是一个好主意,尤其是在专业代码库中。

What you want to do is extend the native Date class:您想要做的是扩展本机Date类:

 class MyCustomDate extends Date { addDays(days) { const date = new MyCustomDate(this.valueOf()); date.setDate(date.getDate() + days); return date; } } const today = new MyCustomDate(); const nextWeek = today.addDays(7) console.log(nextWeek)

This way, if one day Javascript implements a native addDays method, you won't break anything.这样,如果有一天 Javascript 实现了原生addDays方法,您就不会破坏任何东西。

I am using the following solution. 我正在使用以下解决方案。

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 has a constructor that accepts an int. Date具有一个接受int的构造函数。 This argument represents total milliseconds before/after Jan 1, 1970. It also has a method setTime which does the same without creating a new Date object. 此参数表示1970年1月1日之前/之后的总毫秒数。它也具有setTime方法,该方法无需创建新的Date对象即可执行此操作。

What we do here is convert days to milliseconds and add this value to the value provided by getTime. 我们在这里所做的是将天数转换为毫秒,并将此值添加到getTime提供的值中。 Finally, we give the result to Date(milliseconds) constructor or setTime(milliseconds) method. 最后,将结果提供给Date(milliseconds)构造函数或setTime(milliseconds)方法。

Very simple code to add days in date in java script. 非常简单的代码,可以在Java脚本中添加日期。

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

Our team considers date-fns the best library in this space. 我们的团队认为date-fns是该领域中最好的图书馆。 It treats dates as immutable ( Moment.js will probably never adopt immutability ), it's faster, and can be loaded modularly. 它将日期视为不可变的Moment.js可能永远不会采用不可变性 ),它速度更快,并且可以模块化加载。

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

There's a setDate and a getDate method, which allow you to do something like this : 有一个setDategetDate方法,使您可以执行以下操作:

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

If you want to both subtract a number of days and format your date in a human readable format, you should consider creating a custom DateHelper object that looks something like this : 如果您要减去天数并以易于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)); 

(see also this Fiddle ) (另请参阅此小提琴

There is a problem with this kind of functions, I solve it with parseInt()这种函数有问题,我用parseInt()解决

Date.prototype.addDays = function(dias) {

    var date = new Date(this.valueOf());
    date.setDate(parseInt(date.getDate()) + parseInt(dias));
    return date;
}

Date.prototype.addMonths = function(months) {
    var date = new Date(this.valueOf());
    date.setMonth(parseInt(date.getMonth()) + parseInt(months));
    return date;
}


Date.prototype.addYears = function(years) {
    var date = new Date(this.valueOf());
    date.setFullYear(parseInt(date.getFullYear()) + parseInt(years));
    return date;
}

You can try var days = 50;你可以试试var days = 50;

 const d = new Date(); d.setDate(d.getDate() + days)
This should work well 这应该很好用
    //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"

For those using Angular: 对于使用Angular的用户:

Just do: 做就是了:

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

You can create your custom helper function here您可以在此处创建自定义辅助函数

function plusToDate(currentDate, unit, howMuch) {

    var config = {
        second: 1000, // 1000 miliseconds
        minute: 60000,
        hour: 3600000,
        day: 86400000,
        week: 604800000,
        month: 2592000000, // Assuming 30 days in a month
        year: 31536000000 // Assuming 365 days in year
    };

    var now = new Date(currentDate);

    return new Date(now + config[unit] * howMuch);
}

var today = new Date();
var theDayAfterTommorow = plusToDate(today, 'day', 2);

By the way, this is generic solution for adding seconds or minutes or days whatever you want.顺便说一下,这是添加秒、分钟或天的通用解决方案。

Short:短的:

function addDays(date, number) {
    const newDate = new Date(date);
    return new Date(newDate.setDate(newDate.getDate() + number));
}

console.log({
    tomorrow: addDays(new Date(), 1)
});

Advance:进步:


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'),
});

With fix provide by jperljperl提供修复

I've used this approach to get the right date in one line to get the time plus one day following what people were saying above.我已经使用这种方法在一行中获得正确的日期,以便在人们上面所说的之后获得时间加一天。

((new Date()).setDate((new Date()).getDate()+1))

I just figured I would build off a normal (new Date()) :我只是想我会建立一个正常的(new Date())

(new Date()).getDate()
> 21

Using the code above I can now set all of that within Date() in (new Date()) and it behaves normally.使用上面的代码,我现在可以在(new Date()) Date()中设置所有这些,并且它的行为正常。

(new Date(((new Date()).setDate((new Date()).getDate()+1)))).getDate()
> 22

or to get the Date object:或获取Date对象:

(new Date(((new Date()).setDate((new Date()).getDate()+1))))

I can't believe there's no cut'n'paste solution in this thread after 5 years!我不敢相信5 年后在这个线程中没有剪切和粘贴解决方案
SO: To get the same time-of-day regardless of summertime interference: SO:无论夏季干扰如何,都要获得相同的时间:

Date.prototype.addDays = function(days)
    {
    var dat = new Date( this.valueOf() )

    var hour1 = dat.getHours()
    dat.setTime( dat.getTime() + days * 86400000) // 24*60*60*1000 = 24 hours
    var hour2 = dat.getHours()

    if (hour1 != hour2) // summertime occured +/- a WHOLE number of hours thank god!
        dat.setTime( dat.getTime() + (hour1 - hour2) * 3600000) // 60*60*1000 = 1 hour

    return dat
or
    this.setTime( dat.getTime() ) // to modify the object directly
    }

There.那里。 Done!完毕!

function addDays(n){
    var t = new Date();
    t.setDate(t.getDate() + n); 
    var month = "0"+(t.getMonth()+1);
    var date = "0"+t.getDate();
    month = month.slice(-2);
    date = date.slice(-2);
     var date = date +"/"+month +"/"+t.getFullYear();
    alert(date);
}

addDays(5);

The easiest way to get this done is using date-fns library.完成此操作的最简单方法是使用date-fns库。

var addDays = require('date-fns/add_days')
addDays(date, amount)

The documentation is available in this link here .该文档可在此链接中找到 You can also get this done using moment.js .您也可以使用moment.js完成此操作。 The reference link is here参考链接在这里

Hope it helps!希望能帮助到你!

Some implementations to extend Date https://gist.github.com/netstart/c92e09730f3675ba8fb33be48520a86d一些扩展日期的实现https://gist.github.com/netstart/c92e09730f3675ba8fb33be48520a86d

/**
 * just import, like
 *
 * import './../shared/utils/date.prototype.extendions.ts';
 */
declare global {
  interface Date {
    addDays(days: number, useThis?: boolean): Date;

    addSeconds(seconds: number): Date;

    addMinutes(minutes: number): Date;

    addHours(hours: number): Date;

    addMonths(months: number): Date;

    isToday(): boolean;

    clone(): Date;

    isAnotherMonth(date: Date): boolean;

    isWeekend(): boolean;

    isSameDate(date: Date): boolean;

    getStringDate(): string;
  }
}

Date.prototype.addDays = function(days: number): Date {
  if (!days) {
    return this;
  }
  this.setDate(this.getDate() + days);
  return this;
};

Date.prototype.addSeconds = function(seconds: number) {
  let value = this.valueOf();
  value += 1000 * seconds;
  return new Date(value);
};

Date.prototype.addMinutes = function(minutes: number) {
  let value = this.valueOf();
  value += 60000 * minutes;
  return new Date(value);
};

Date.prototype.addHours = function(hours: number) {
  let value = this.valueOf();
  value += 3600000 * hours;
  return new Date(value);
};

Date.prototype.addMonths = function(months: number) {
  const value = new Date(this.valueOf());

  let mo = this.getMonth();
  let yr = this.getYear();

  mo = (mo + months) % 12;
  if (0 > mo) {
    yr += (this.getMonth() + months - mo - 12) / 12;
    mo += 12;
  } else {
    yr += ((this.getMonth() + months - mo) / 12);
  }

  value.setMonth(mo);
  value.setFullYear(yr);
  return value;
};

Date.prototype.isToday = function(): boolean {
  const today = new Date();
  return this.isSameDate(today);
};

Date.prototype.clone = function(): Date {
  return new Date(+this);
};

Date.prototype.isAnotherMonth = function(date: Date): boolean {
  return date && this.getMonth() !== date.getMonth();
};

Date.prototype.isWeekend = function(): boolean {
  return this.getDay() === 0 || this.getDay() === 6;
};

Date.prototype.isSameDate = function(date: Date): boolean {
  return date && this.getFullYear() === date.getFullYear() && this.getMonth() === date.getMonth() && this.getDate() === date.getDate();
};

Date.prototype.getStringDate = function(): string {
  // Month names in Brazilian Portuguese
  const monthNames = ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'];
  // Month names in English
  // let monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
  const today = new Date();
  if (this.getMonth() === today.getMonth() && this.getDay() === today.getDay()) {
    return 'Hoje';
    // return "Today";
  } else if (this.getMonth() === today.getMonth() && this.getDay() === today.getDay() + 1) {
    return 'Amanhã';
    // return "Tomorrow";
  } else if (this.getMonth() === today.getMonth() && this.getDay() === today.getDay() - 1) {
    return 'Ontem';
    // return "Yesterday";
  } else {
    return this.getDay() + ' de ' + this.monthNames[this.getMonth()] + ' de ' + this.getFullYear();
    // return this.monthNames[this.getMonth()] + ' ' + this.getDay() + ', ' +  this.getFullYear();
  }
};


export {};
date d = new Date() // current date

date tomorrow = d.setMonth(d.getMonth(),d.getDate()+1) // return a date incremented by 0 months and 1 day
new Date(Date.now() + 2000 * 86400)

This snippet adds two days to the current date using the "2000" argument.此代码段使用“2000”参数将两天添加到当前日期。 You can tweak the number of days by updating the "2000" value in the second argument.您可以通过更新第二个参数中的“2000”值来调整天数。

You can use this single line format to add days to the current date using the native JavaScript date.您可以使用此单行格式将天数添加到使用本机 JavaScript 日期的当前日期。

2.39KB minified. 2.39KB 缩小。 One file.一档。 https://github.com/rhroyston/clock-js https://github.com/rhroyston/clock-js

 console.log(clock.what.weekday(clock.now + clock.unit.days)); //"wednesday" console.log(clock.what.weekday(clock.now + (clock.unit.days * 2))); //"thursday" console.log(clock.what.weekday(clock.now + (clock.unit.days * 3))); //"friday"
 <script src="https://raw.githubusercontent.com/rhroyston/clock-js/master/clock.min.js"></script>

try this尝试这个

function addDays(date,days) {        
      var one_day=1000*60*60*24; 
      return new Date(date.getTime()+(days*one_day)).toLocaleDateString(); 
    }

Use js-joda .使用js-joda It is an awesome immutable date and time library for javascript .它是一个很棒的javascript不可变日期和时间库。 Here is an excerpt from its cheat-sheet.这是其备忘单的摘录。

Add 17 days to today增加 17 天到今天

LocalDate.now().plusDays(17); 

You can also build the desired date from now multiple operations at once.您还可以从现在开始一次构建多个操作所需的日期。

LocalDate.now()
  .plusMonths(1)
  .withDayOfMonth(1)
  .minusDays(17); 

Or:或者:

var d = LocalDate.parse('2019-02-23'); 
d.minus(Period.ofMonths(3).plusDays(3)); // '2018-11-20'

My test exemple can do adition an minus in the same instance of Date Object.我的测试示例可以在 Date 对象的同一实例中添加减号。

 Date.prototype.reset = function() { let newDate = new Date(this.timeStamp) this.setFullYear (newDate.getFullYear()) this.setMonth (newDate.getMonth()) this.setDate (newDate.getDate()) this.setHours (newDate.getHours()) this.setMinutes (newDate.getMinutes()) this.setSeconds (newDate.getSeconds()) this.setMilliseconds (newDate.getMilliseconds()) } Date.prototype.addDays = function(days) { this.timeStamp = this[Symbol.toPrimitive]('number') let daysInMiliseconds = (days * (1000 * 60 * 60 * 24)) this.timeStamp = this.timeStamp + daysInMiliseconds this.reset() } Date.prototype.minusDays = function(days) { this.timeStamp = this[Symbol.toPrimitive]('number') let daysInMiliseconds = (days * (1000 * 60 * 60 * 24)) if(daysInMiliseconds <= this.timeStamp) { this.timeStamp = this.timeStamp - daysInMiliseconds this.reset() } } var temp = new Date(Date.now())// from now time console.log(temp.toDateString()) temp.addDays(31) console.log(temp.toDateString()) temp.minusDays(5) console.log(temp.toDateString())

I was trying to solve something similar, I prefer the getTime methods but there are some odd time zone based side effects.我试图解决类似的问题,我更喜欢 getTime 方法,但是有一些基于时区的奇怪副作用。

ofc replace "today" with whatever date you need and pass the time in also. ofc 将“今天”替换为您需要的任何日期,并打发时间。 The key is to get UTC Time and then use milliseconds to do the addition to bypass those side effects.关键是获取 UTC 时间,然后使用毫秒进行添加以绕过这些副作用。

var now = new Date(Date.now());
var today = new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate()));

const dayInMs = 86400000; //24 hours
const tomorrow = new Date(today.getTime() + dayInMs);    

I sum hours and days...我总结了几个小时和几天...

Date.prototype.addDays = function(days){
    days = parseInt(days, 10)
    this.setDate(this.getUTCDate() + days);
    return this;
}

Date.prototype.addHours = function(hrs){
    var hr = this.getUTCHours() + parseInt(hrs  , 10);
    while(hr > 24){
      hr = hr - 24;
      this.addDays(1);
    }

    this.setHours(hr);
    return this;
}

For everybody who don't know how to make it work : there is a full working code it's not perfect but you can copy past it and it's working.对于不知道如何使其工作的每个人:有一个完整的工作代码,它并不完美,但您可以复制它并且它正在工作。

In InDesign creat a .jsx in the startup scripts folder in "Program Files\\Adobe\\Adobe InDesign 2021\\Scripts\\startup scripts" .在 InDesign 中,在"Program Files\\Adobe\\Adobe InDesign 2021\\Scripts\\startup scripts"的启动脚本文件夹中创建一个.jsx

You can us the Extendscript Toolkit CC in the creative cloud to make it and paste this:您可以使用创意云中的 Extendscript Toolkit CC 制作并粘贴此内容:

The restart indesign and jjmmyyyy +30 should be in the texte variable.重新启动 indesign 和jjmmyyyy +30 应该在 texte 变量中。 this will show the date like this jj/m/yyyy idk how to make it show 24/07/2021 insted of 24/7/2021 but goodenough for me .这将显示像这样的日期jj/m/yyyy idk 如何让它显示24/07/2021 24/7/2021但对我来说24/7/2021足够了。

    #targetengine 'usernameVariable'
    function addVariables(openEvent) 
    {  
    var doc = openEvent.parent;  
    while ( doc.constructor.name != "Document" )  
      {  
    if ( doc.constructor.name == "Application" ){ return; }  
        doc = doc.parent;  
      }  
    // from http://stackoverflow.com/questions/563406/add-days-to-datetime


    var someDate = new Date();
    var numberOfDaysToAdd = 30;
    someDate.setDate(someDate.getDate() + numberOfDaysToAdd); 


    var dd = someDate.getDate();
    var mm = someDate.getMonth() + 1;
    var y = someDate.getFullYear();

    var someFormattedDate = dd + '/'+ mm + '/'+ y;  

      createTextVariable(doc, "jjmmyyyy+30", someFormattedDate);  
    }
    function createTextVariable(target, variableName, variableContents)  
    {  
    var usernameVariable = target.textVariables.itemByName(variableName);  
    if (!usernameVariable.isValid)  
      {  
        usernameVariable = target.textVariables.add();  
        usernameVariable.variableType = VariableTypes.CUSTOM_TEXT_TYPE;  
        usernameVariable.name = variableName;  
      }  
      usernameVariable.variableOptions.contents = variableContents;  
    }  
    app.addEventListener('afterOpen', addVariables);

the same answer: How to add number of days to today's date?相同的答案: 如何将天数添加到今天的日期?

    function DaysOfMonth(nYear, nMonth) {
        switch (nMonth) {
            case 0:     // January
                return 31; break;
            case 1:     // February
                if ((nYear % 4) == 0) {
                    return 29;
                }
                else {
                    return 28;
                };
                break;
            case 2:     // March
                return 31; break;
            case 3:     // April
                return 30; break;
            case 4:     // May
                return 31; break;
            case 5:     // June
                return 30; break;
            case 6:     // July
                return 31; break;
            case 7:     // August
                return 31; break;
            case 8:     // September
                return 30; break;
            case 9:     // October
                return 31; break;
            case 10:     // November
                return 30; break;
            case 11:     // December
                return 31; break;
        }
    };

    function SkipDate(dDate, skipDays) {
        var nYear = dDate.getFullYear();
        var nMonth = dDate.getMonth();
        var nDate = dDate.getDate();
        var remainDays = skipDays;
        var dRunDate = dDate;

        while (remainDays > 0) {
            remainDays_month = DaysOfMonth(nYear, nMonth) - nDate;
            if (remainDays > remainDays_month) {
                remainDays = remainDays - remainDays_month - 1;
                nDate = 1;
                if (nMonth < 11) { nMonth = nMonth + 1; }
                else {
                    nMonth = 0;
                    nYear = nYear + 1;
                };
            }
            else {
                nDate = nDate + remainDays;
                remainDays = 0;
            };
            dRunDate = Date(nYear, nMonth, nDate);
        }
        return new Date(nYear, nMonth, nDate);
    };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM