Instead of using asHours
and round with Math.floor
, you can just use hours
(as indicated in the documentation, the getters that begin with as
return the full duration, while its versions without as
return already rounded values).
Same goes for minutes: instead of using moment.utc
, use minutes
. The formatting would look like this:
var s = d.hours() + "h " + d.minutes().toString().padStart(2, '0') +"m";
And to get the total in minutes, you can use asMinutes
:
var dtChegada = "16:40";
var dtPartida = "11:20";
var ms = moment(dtChegada, "HH:mm").diff(moment(dtPartida, "HH:mm"));
var d = moment.duration(ms);
var s = d.hours() + "h " + d.minutes().toString().padStart(2, '0') +"m";
console.log("Formatado: " + s);
console.log("Total em minutos: " + d.asMinutes());
<script src="https://momentjs.com/downloads/moment.min.js"></script>
I just used padStart
in the minutes to be shown with zero on the left if the value is less than 10 (you can do the same with the hours if you want).
Attention: do not use moment.utc
in this case
Remember that when using moment.utc
you are actually creating a date (and no longer a duration), which coincidentally has the value of minutes equal to the amount of minutes of the duration. But in general you should not mix things.
A date/time represents a point in the timeline (a date is a specific point in the calendar, a time is a specific time of the day). A duration is a quantity of time, without any relation to calendars ("it is two in the afternoon" is a time, a specific time of the day, already "the film has two hours of duration" is a duration: a quantity of time, does not say what hours start or end, only how long lasts).
That’s why there’s a moment.duration
, since durations are different from a date, and you shouldn’t mix things up, even if "it works".
But of course you can also do without moment
:
function totalMinutos(horario) {
const [h, m] = horario.split(':').map(v => parseInt(v));
return h * 60 + m;
}
var dtChegada = "16:40";
var dtPartida = "11:20";
// diferença dá o total em minutos
var diff = totalMinutos(dtChegada) - totalMinutos(dtPartida);
console.log(`Total em minutos: ${diff}`);
var h = Math.floor(diff / 60);
var m = diff % 60;
var formatado = `${h}h ${m.toString().padStart(2, "0")}m`;
console.log(`Formatado: ${formatado}`);