Reputation: 27
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
Upvotes: 2
Views: 86
Reputation: 147453
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)
Upvotes: 0
Reputation: 16831
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`)
})();
Upvotes: 1