javascriptangularjsdate-formatisodate

how to add an extra day to the iso format date in javascript


Current date Format :2016-05-10T06:34:17Z,I need to add 10 days to the current date ie..2016-05-20T06:34:17 in javascript or in angularjs.


Solution

  • You can create a new date based on your string using Date constructor.

    Use Date.prototype.setDate() to set the day of the Date.

    Example:

    var myDate = new Date('2016-05-10T06:34:17Z');
    myDate.setDate(myDate.getDate() + parseInt(10));
    console.log(myDate);

    Notes: You can create simple "utility" function if you need to use more times this script, example:

    var addDays = function(str, days) {
      var myDate = new Date(str);
      myDate.setDate(myDate.getDate() + parseInt(days));
      return myDate;
    }
    
    var myDate = addDays('2016-05-10T06:34:17Z', 10);
    console.log(myDate);

    Related documentation:

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate