Luxon HH:mm 日期时间之间的差异
Luxon HH:mm difference between datetimes
用 luxon 替换 moment 并想要 HH:mm 中的日期时间之间的差异。有更好的方法吗?
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
end.diff(start, "seconds", "minutes").toFormat("hh:mm"); // => 6:01
您可以使用 duration.toFormat()
获得相同的结果。使用功能方法:
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/luxon@2.1.1/build/global/luxon.min.js"></script>
用 luxon 替换 moment 并想要 HH:mm 中的日期时间之间的差异。有更好的方法吗?
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
end.diff(start, "seconds", "minutes").toFormat("hh:mm"); // => 6:01
您可以使用 duration.toFormat()
获得相同的结果。使用功能方法:
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/luxon@2.1.1/build/global/luxon.min.js"></script>