# Finding number of days until a certain date

I'm using Node.js and Moment in order to retrieve the days until the next 8th:

const getDaysTillSalary = (day) => {
const today = moment();
const currentDay = moment().format('D');
let currentMonth = moment().format('M');
let currentYear = moment().format('Y');
const isCurrentDayGreater = parseInt(currentDay) > day;

currentYear = isCurrentDayGreater && parseInt(currentMonth) === 12 ? moment().add(1, 'year').format('Y') : currentYear;
currentMonth = isCurrentDayGreater ? moment().add(1, 'months').format('M') : currentMonth;

const salaryDate = moment(${day}-${currentMonth}-\${currentYear}, 'DD-MM-YYYY');

return salaryDate.diff(today, 'days');
}

getDaysTillSalary(8);


I'm sure there is a cleaner and maybe efficient way to solve this problem, and will be glad to get some feedback.

## 1 Answer

const currentDay = moment().format('D');


You use .format() a lot, instead use Moment.js's getters like .date(). This way you also don't have to use parseInt() since the getters return number's.

What about this solution:

const getDaysTillSalary = (day) => {
let date = moment();
let days = 0;
while(date.date() !== 8) {
date = date.add(1, 'day');
days++;
}
return days;
}


It creates a variable and stores the current Moment.js date in it. Then it repeatedly adds one day using .add() and counts up until date.date() (the day of the month) returns 8. The days variable is then returned.

• I downvoted your answer because you neither review the code nor explained what you did. – t3chb0t Dec 9 '17 at 19:28
• @t3chb0t I'm new to the Code Review community. I added some feedback and explained my solution. – Niklas Higi Dec 9 '17 at 20:02
• Well done. Now I can undo the vote ;-) – t3chb0t Dec 9 '17 at 20:08