I'm trying to calculate the number of days between two dynamic dates.
I have a product where credits are renewed the day 19th, and I want to show the user how many days remain to renew them.
I have tried this code with no success: if today it's November 22nd, the result that this code returns is a negative number, when it should return "27" as there are 27 days between today and December 19th.
var today = new Date();
var todayMonth = today.getMonth()+1;
if(todayMonth<10) todayMonth = 0+todayMonth;
var datetwo = new Date(today.getFullYear()+"-"+todayMonth+"-19T00:00:00.000Z");
var dayDif = (datetwo - today) / 1000 / 60 / 60 / 24;
dayDif = Math.ceil(dayDif);
var daysLeftRenew = dayDif;
I also tried with Moment.js, but I cannot find how to work with dynamic dates like this.
if today it's November 22nd, the result that this code returns is a negative number, when it should return "27" as there are 27 days between today and December 19th.
You need to change this line
var todayMonth = today.getMonth()+1;
to
var todayMonth = today.getMonth()+2;//2 instead of 1 as getMonth will give value starting from 0 to 11.
since you are setting the month parameter within the string format and it will take the month parameter as is.
Demo
var today = new Date(); var todayMonth = today.getMonth() + 2; if (todayMonth < 10) todayMonth = 0 + todayMonth; var datetwo = new Date(today.getFullYear() + "-" + todayMonth + "-19T00:00:00.000Z"); var dayDif = (datetwo - today) / 1000 / 60 / 60 / 24; dayDif = Math.ceil(dayDif); var daysLeftRenew = dayDif; console.log(daysLeftRenew);
Dates manipulation may be tricky, you can consider using dedicated library for such computations like moment.js . It will also make code code much more clean:
var targetDate = moment().date(19); if (targetDate.isBefore(moment())) { targetDate.add(1, 'month'); } console.log(targetDate.endOf('day').fromNow());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.2/moment.min.js"></script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.