Add days to JavaScript Date

2018-12-31 00:57发布

How to add days to current Date using JavaScript. Does JavaScript have a built in function like .Net's AddDay?

30条回答
残风、尘缘若梦
2楼-- · 2018-12-31 01:19

There's a setDate and a getDate method, which allow you to do something like this :

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 :

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)

查看更多
流年柔荑漫光年
3楼-- · 2018-12-31 01:22

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;
}
查看更多
若你有天会懂
4楼-- · 2018-12-31 01:23

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

// 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>

查看更多
唯独是你
5楼-- · 2018-12-31 01:23

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.

查看更多
荒废的爱情
6楼-- · 2018-12-31 01:23

Edit: Instead of setTime() (or setHours()) you could do it this way:

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():

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

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

See the JSFiddle...

查看更多
梦该遗忘
7楼-- · 2018-12-31 01:23

For those using Angular:

Just do:

$scope.booking.totTijd.setMinutes($scope.booking.totTijd.getMinutes()+15);
$scope.booking.totTijd.setDate($scope.booking.totTijd.getDate() + 1);
查看更多
登录 后发表回答