Search code examples
angularangular6angular5angular7

how to calculate the duration using a date - angular 2+


Api ,

{
   data:{
      "duration": 12,
      "startDate": "27-01-2020 16:09"
   }
}

I am using angular 2+..I api, duration is 12( in month) and given the startdate...

Task:-

I have to calculate the expiring days(license is expiring in DD days). So have to subtract the today's date from startDate(in api)..

Can anybody help me?


Solution

  • Try this:

    data = {
      data: {
        "duration": 12,
        "startDate": "27-01-2020 16:09"
      }
    };
    
    var date1 = new Date();
    
    var nDate = String(data.data.startDate);
    var onlyDate = nDate.split(" ");
    
    var dParts = onlyDate[0].split("-");
    
    var date2 = new Date(dParts[2] + '-' + dParts[1] + "-" + dParts[0]);
    console.log(date1);
    console.log(date2);
    var timeDiff = Math.abs(date2.getTime() - date1.getTime());
    var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
    console.log(diffDays);

    My fiddle