I have an object that rapresent the time difference between a date and now (I used 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. 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));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.