1

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.

Harish98
  • 445
  • 1
  • 7
  • 16
  • 3
    Possible duplicate of [Add days to JavaScript Date](http://stackoverflow.com/questions/563406/add-days-to-javascript-date) – Jokab Jul 29 '16 at 09:28

2 Answers2

4

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

GibboK
  • 71,848
  • 143
  • 435
  • 658
  • Thanks GibboK. I got it. – Harish98 Jul 29 '16 at 09:35
  • Why the `parseInt()`? `.getDate()` returns an integer, so it should be safe to do `myDate.getDate() + 10`. – Arnauld Jul 29 '16 at 09:40
  • @HarishKesari thanks for your comment, if you think my answer as helped you out please do not forget to accept it or upvote it using the "Arrow" and "Tick" on the left side :) thanks! – GibboK Jul 29 '16 at 09:52
  • @Arnauld I got your point. I added in case a user pass a string instead of number like addDays('2016-05-10T06:34:17Z', '10'); – GibboK Jul 29 '16 at 09:54
3

One Liner Solution:

  • Today:

    today = new Date().toISOString()

  • Yesterday:

    yesterday = new Date(new Date().setDate(new Date().getDate() - 1)).toISOString()

  • Tomorrow:

    tomorrow = new Date(new Date().setDate(new Date().getDate() + 1)).toISOString()

Tip: You can add or subtract days to get the exact date from today.