2

this code already gets the days until x date but it keeps counting when x date reaches the same date, how can I zero it out to stop counting?

const counters = this.state.counters.map((counters, i) => {
  let untildate = counters.date
  let diffDays1=(function(){ 
    let oneDay = 24*60*60*1000 // hours*minutes*seconds*milliseconds
    let secondDate = new Date(untildate);
    let firstDate = new Date();
    return (`${Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)))} Days`)
  })();

If the input date is 2019-04-05T20:00:00.782Z the out put should be 0

HDaniel999
  • 27
  • 5
  • You can probably accomplish what you want using `Math.max(0, ...)` so that if the number of days remaining is negative (less than 0) it will return 0 (which is larger than a negative number) – stevendesu May 13 '19 at 18:46
  • @stevendesu Thank you very much! It actually works! :D – HDaniel999 May 13 '19 at 19:14
  • Why not just `if (daysRemaining < 1) return 0`? Why are you using an IIFE, why not just inline the code? – RobG May 14 '19 at 06:53

2 Answers2

1

Use Math.max to return the larger of two values. In your case, you want to return the number of days remaining only if that number is greater than 0, otherwise you want to return 0:

const counters = this.state.counters.map((counters, i) => {
  let untildate = counters.date
  let diffDays1=(function(){ 
    let oneDay = 24*60*60*1000 // hours*minutes*seconds*milliseconds
    let secondDate = new Date(untildate);
    let firstDate = new Date();
    return (`${Math.max(0, Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay))))} Days`)
  })();
stevendesu
  • 15,753
  • 22
  • 105
  • 182
0

There are many answers for how to get the difference between two dates in days, like this.

Your code seems overly convoluted. Assuming the input dates are in a format like 2019-05-10 and you're using the built-in parser, you can work in UTC and avoid any daylight saving issues.

Just test the difference in days, if it's 0 or less, return zero. Otherwise, return the difference. E.g.

var dates = ['2019-01-01','2019-05-10','2019-05-20'];

var counters = dates.map(date => {
  let diffDays = (new Date(date) - new Date().setUTCHours(0,0,0,0))/8.64e7;
  return diffDays > 0? diffDays : 0;
});

console.log(counters)
RobG
  • 142,382
  • 31
  • 172
  • 209