Search code examples
javascriptluxon

Luxon HH:mm difference between datetimes


Replacing moment with luxon and want the difference between to datetimes in HH:mm. Is there a better way to do this?

const DateTime = luxon.DateTime;
const Interval = luxon.Interval;

const format1 = "yyyy-MM-dd HH:mm";
var time1 = '2021-11-22 10:11';
var time2 = '2021-11-22 16:12';
var start = DateTime.fromFormat(time1,format1);
var end =  DateTime.fromFormat(time2,format1);
var diff = end.diff(start);
var i = Interval.fromDateTimes(start, end);
var sec = i.length('seconds') ;
var hours = Math.floor(sec / 60 / 60);
var minutes = Math.floor(sec / 60) - (hours * 60);
var formatted = hours.toString().padStart(2, '0') + ':' + minutes.toString().padStart(2, '0'); //"HH:mm"
alert(formatted); //06:01

Solution

  • end.diff(start, "seconds", "minutes").toFormat("hh:mm"); // => 6:01