I am using below logic to calculate the time difference
.
However, this is giving wrong result value when days > 1
.
Please help simplifying the code.
I will be using the time difference logic in angular framework.
const startDate = new Date(form.value.startDate);
const endDate = new Date();
const dateDiff = this.calculateDateDifference(startDate, endDate);
calculateDateDifference(startDate, endDate) {
const difference = endDate.getTime() - startDate.getTime();
const seconds = Math.floor((difference / 1000) % 60);
const minutes = Math.floor((difference / (1000 * 60)) % 60);
const hours = Math.floor((difference / (1000 * 60 * 60)) % 24);
const days = Math.floor(difference / (1000 * 60 * 60 * 24));
console.log(days + ' days ' + hours + ' hours ' + minutes + ' minutes ' + seconds + ' seconds');
if (days > 1) {
return `${days} Days, ${hours} Hours, ${minutes} Mins`;
} else {
return `${hours} Hours, ${minutes} Mins`;
}
}
How can I achieve the same output using "moment"?
2
Answers
As mentioned by jabaa, you should avoid moment.js as it is now in a maintenance state.
You can try out day.js which is a modern equivalent and won’t require a lot of effort to modify your code.
You can install it via yarn/npm with the package name
dayjs
You can then write something like:
I appreciate you mentioned angular, to allow the running on Stackoverflow I just used plain JS and HTML, but this should work on Angular also.
maybe it is useful for you I converted that code in the moment