0

i really stuck at this date. Let say today is 01 20 2021, and i want to add 14 day later to get expired date. so for the expired date should be 02 03 2021, but i only get 01 03 2021. Can anyone help me on this. Thanks

this is my code

    var today = new Date();
  
    var monthIndex = today.getMonth()+1;
    var year = today.getFullYear();

    var addday = new Date(new Date('1.20.2021').getTime()+(14*24*60*60*1000));
    var nextDay = addday.getDate();
    var nextMonth = monthIndex;
    console.log('day',day)
    
    return nextMonth+'.'+nextDay+'.'+year
 
    //the return that I want is 2.03.2021


Rexz
  • 3
  • 1
  • You're mixing the current date and a set date `1/20/2021`. Why? Also you can just use `addday` to get the month, day, and year with `getDay()`, `getMonth()`, and `getFullYear()`. Month is zero-based in JS dates. [More info](https://stackoverflow.com/questions/2552483/why-does-the-month-argument-range-from-0-to-11-in-javascripts-date-constructor) – Liftoff Oct 01 '21 at 04:27
  • Check for momentjs it has easy to use lib functions to operate on dates. https://momentjs.com/ – Prashant Oct 01 '21 at 04:53
  • Re `new Date('1.20.2021')`, see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG Oct 01 '21 at 08:51

2 Answers2

1

You didnt update the value for monthIndex. You must use:

var nextMonth = addday.getMonth()+1;
Wolfgang Amadeus
  • 398
  • 3
  • 12
-1

Just use Date.setDate function for this.

// new Date('1.20.2021') => Jan 20 2021
const dateStr = '1.20.2021';
const [mm, dd, yyyy] = dateStr.split('.');
const today = new Date(yyyy, +mm-1, dd);
// add 14 days
const newDate = new Date(new Date(today).setDate(today.getDate() + 14));
console.log(`Today: ${today}`);
console.log(`New Date: ${newDate}`);
console.log(newDate.getMonth() + 1 + '.' + newDate.getDay() + '.' + newDate.getFullYear());
Nitheesh
  • 19,238
  • 3
  • 22
  • 49