【问题标题】:Luxon HH:mm difference between datetimesLuxon HH:mm 日期时间之间的差异
【发布时间】:2022-01-01 17:33:33
【问题描述】:

用 luxon 替换时刻,并希望以 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

【问题讨论】:

    标签: javascript luxon


    【解决方案1】:
    end.diff(start, "seconds", "minutes").toFormat("hh:mm"); // => 6:01
    

    【讨论】:

    • 谢谢。这帮助我取代了我的旧时光。
    【解决方案2】:

    您可以使用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>

    【讨论】:

    • 谢谢。这个很干净,效果很好。
    猜你喜欢
    • 2012-02-04
    • 2021-07-18
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    • 2011-02-01
    • 1970-01-01
    • 2021-03-08
    • 2012-06-26
    相关资源
    最近更新 更多