简体   繁体   English

以人类可读的格式显示两个日期之间的差异

[英]Difference between two date in an human readable format

I have an object that rapresent the time difference between a date and now (I used Luxon): 我有一个表示日期和现在之间的时差的对象(我使用了Luxon):

{days: -0, hours: -15, minutes: -38, months: -0, seconds: -46.389, years: -0}

and I want to print that information in an human readable way. 我想以一种人类可读的方式打印这些信息。 So, in this case: 因此,在这种情况下:

difference is 15 h, 38 min, 46 s

So, I wouldn't consider numbers equals to 0 and the result should be sorted so years, months, days, hours, minutes, seconds. 因此,我不会认为数字等于0,并且应该对结果进行排序,以使其为年,月,日,小时,分钟,秒。 What is the smarter way to do that? 什么是更聪明的方法呢?

you can use something like this 你可以用这样的东西

function toReadable(obj) {
    var names = {
        days: "d", hours: 'h', minutes: 'min', months: 'm', seconds: 's', years: 'y'
    }
    return Object.keys(obj).reduce((acc, v) => {
        if(obj[v] != 0) acc.push(Math.abs(Math.ceil(obj[v])) + ' ' + names[v]);
        return acc;
    }, []).join(', ')
}

Since you can't guarantee order in an object, you can keep the order in an array and use some logic for the modified names, eg 由于不能保证对象的顺序,因此可以将顺序保留在数组中,并对修改后的名称使用一些逻辑,例如

 function formatPeriod(obj) { return ['years','months','days','hours','minutes','seconds'].reduce((acc, key) => { let v = parseInt(Math.abs(obj[key])); if (v != 0) acc.push(v + ' ' + key.slice(0,key=='minutes'?3:1)); return acc; }, []).join(', '); } // Example var data = {days: -0, hours: -15, minutes: -38, months: -0, seconds: -46.389, years: -0}; console.log(formatPeriod(data)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM