Get days, hour and minutes diff moment js
As moment.asDays(date)
return float you need to use Math.floor()
function durationAsString(start, end) {
const duration = moment.duration(moment(end).diff(moment(start)));
//Get Days
const days = Math.floor(duration.asDays()); // .asDays returns float but we are interested in full days only
const daysFormatted = days ? `${days}d ` : ''; // if no full days then do not display it at all
//Get Hours
const hours = duration.hours();
const hoursFormatted = `${hours}h `;
//Get Minutes
const minutes = duration.minutes();
const minutesFormatted = `${minutes}m`;
return [daysFormatted, hoursFormatted, minutesFormatted].join('');
}
console.log(durationAsString('2018-03-28 14:02', '2018-06-02 00:00'))
console.log(durationAsString('2018-06-01 14:02', '2018-06-02 00:00'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>
Not directly within moment.js, no, but this open issue led me to this moment.js plugin which allows formatting of durations. Looks like with that plugin you could use this to get your desired output:
duration.format("D [day], H [hour and] m [min]")
Without a plugin:
var now = moment('2018-03-28 14:02');
var end = moment('2018-06-02 00:00'); // another date
var duration = moment.duration(end.diff(now));
//Get Days and subtract from duration
var days = duration.asDays();
duration.subtract(moment.duration(days,'days'));
//Get hours and subtract from duration
var hours = duration.hours();
duration.subtract(moment.duration(hours,'hours'));
//Get Minutes and subtract from duration
var minutes = duration.minutes();
duration.subtract(moment.duration(minutes,'minutes'));
//Get seconds
var seconds = duration.seconds();
console.log("Days: ",days);
console.log("Hours: ",hours);
console.log("Minutes: ",minutes);
console.log("Seconds: ",seconds);