Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 240
Aruru Avatar asked Jul 13 '26 22:07

Aruru


2 Answers

You can achieve the same result using duration.toFormat(). Using a functional appraoch:

const {DateTime} = luxon;

function parseDT (dt, format = 'yyyy-MM-dd HH:mm') {
  // You can optionally implement any datetime string validation here
  return DateTime.fromFormat(dt, format);
}

function getDurationString (dt1, dt2, format = 'hh:mm') {
  return parseDT(dt2).diff(parseDT(dt1)).toFormat(format);
}

console.log(getDurationString('2021-11-22 10:11', '2021-11-22 16:12')); // 06:01
console.log(getDurationString('2021-11-01 10:00', '2021-12-01 10:00')); // 721:00
<script src="https://unpkg.com/[email protected]/build/global/luxon.min.js"></script>
like image 198
jsejcksn Avatar answered Jul 16 '26 12:07

jsejcksn


end.diff(start, "seconds", "minutes").toFormat("hh:mm"); // => 6:01
like image 36
snickersnack Avatar answered Jul 16 '26 12:07

snickersnack