Advertisement
tonysamperi

010 - Humanized duration

Aug 16th, 2022
940
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 0.76 KB | Source Code | 0 0
  1. import {DateTime} from "ts-luxon";
  2.  
  3. function humanizedDuration(d1, d2, maxUnit = "days") {
  4.   const units = [
  5.     "weeks", "days", "hours", "minutes", "seconds"
  6.   ];
  7.   const maxUnitIndex = maxUnit.indexOf(maxUnit);
  8.   const diff = DateTime
  9.       .fromJSDate(rawJsDate)
  10.       .diff(DateTime.fromMillis(+rawJsDate))
  11.       .toFormat(
  12.         ["ww", "dd", "hh", "mm", "ss"]      
  13.           .slice(maxUnitIndex)
  14.           .join(" ")
  15.       )
  16.       .split(" ");
  17.  
  18.   return units
  19.     .slice(maxUnitIndex)
  20.     .map((u, i) => `${diff[i]}${u.slice(0, 1)}`)
  21.     .filter((v, i) => !~["weeks", "days"].indexOf(v) || diff[i] !== 0)
  22.     .join(" ")
  23. }
  24.  
  25. const now = new Date();
  26. console.info(humanizedDuration(
  27.   now, new Date(+now +(1000*3600*48)))
  28. );
  29. // output: 1d 23h 59m 59s
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement