Display negative days in calculation between dates

Asked

Viewed 57 times

1

I’m doing a list of accounts receivable.

To get interactive, I’m creating an IF to show when it’s near.

Problem

Shows no negative date, which would represent overdue invoice.

In this case the low image, today are 08/02/2020, the tag that should be shown, is the Vencido.

mostrando resultado errado

Code

if (data[5] == null) {
  hoje = new Date('<?= date('Y - m - d '); ?>');
  data = new Date(data[4]);
  diferenfa = Math.abs(data.getTime() - hoje.getTime());
  nDias = Math.ceil(diferenfa / (1000 * 3600 * 24));

  if (nDias >= 8) {
    return '<span class="label">Faltam ' + nDias + ' dias</span>';

  } else if (nDias <= 7 && nDias >= 3) {
    return '<span class="label label-warning">Está proximo</span>';

  } else if (nDias <= 2 && nDias >= 1) {
    return '<span class="label label-sm label-yellow">Amanhã</span>';

  } else if (nDias == 0) {
    return '<span class="label label-info">Hoje</span>';

  }else if (nDias < 0){
    return '<span class="label label-info">Vencido</span>';
  }



} else {
  return '<span class="label label-success">Pago</span>';
}

Question

How can I ride these ifs so that it works correctly?

1 answer

3


The biggest problem seems to be the adopted formula. I did not use the function abs() that removes the signal. If the result is expired it is negative, with this function any negative number turns positive, then it does not fall in the if correct.

I changed some things to make the test easier, but others was just code simplification.

var hoje = new Date(new Date().toDateString());
var data = new Date(new Date(2020, 1, 7).toDateString());
var nDias = Math.ceil((data - hoje) / (1000 * 3600 * 24));
if (nDias > 7) console.log('<span class="label">Faltam ' + nDias + ' dias</span>');
else if (nDias > 2) console.log('<span class="label label-warning">Está proximo</span>');
else if (nDias > 0) console.log('<span class="label label-sm label-yellow">Amanhã</span>');
else if (nDias == 0) console.log('<span class="label label-info">Hoje</span>');
else console.log('<span class="label label-info">Vencido</span>');

I put in the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.