Convert seconds to compound duration: Difference between revisions

m (→‎{{header|Phix}}: added timedelta example)
Line 2,284:
6000000 secs = 9 wk, 6 d, 10 hr, 40 min,
</pre>
 
=={{header|Nim}}==
<lang Nim>from strutils import addSep
 
const
Units = [" wk", " d", " hr", " min", " sec"]
Quantities = [7 * 24 * 60 * 60, 24 * 60 * 60, 60 * 60, 60, 1]
 
#---------------------------------------------------------------------------------------------------
 
proc `$$`*(sec: int): string =
## Convert a duration in seconds to a friendly string.
 
doAssert(sec > 0)
 
var duration = sec
var idx = 0
while duration != 0:
let q = duration div Quantities[idx]
if q != 0:
duration = duration mod Quantities[idx]
result.addSep(", ", 0)
result.add($q & Units[idx])
inc idx
 
#———————————————————————————————————————————————————————————————————————————————————————————————————
 
when isMainModule:
for sec in [7259, 86400, 6000000]:
echo sec, "s = ", $$sec</lang>
 
{{out}}
<pre>7259s = 2 hr, 59 sec
86400s = 1 d
6000000s = 9 wk, 6 d, 10 hr, 40 min</pre>
 
===Using the “times” module===
 
It is also possible to use the Duration type in the “times” module and the procedure “toParts” which decomposes a duration in units of time (nanoseconds, microseconds, milliseconds, seconds, minutes, hours, days and weeks).
 
<lang Nim>import times
from algorithm import reversed
from strutils import addSep
 
const Units = [" wk", " d", " hr", " min", " sec"]
 
#---------------------------------------------------------------------------------------------------
 
proc `$$`*(sec: int): string =
## Convert a duration in seconds to a friendly string.
## Similar to `$` but with other conventions.
 
doAssert(sec > 0)
 
var duration = initDuration(seconds = sec)
let parts = reversed(duration.toParts[Seconds..Weeks])
 
for idx, part in parts:
if part != 0:
result.addSep(", ", 0)
result.add($part & Units[idx])
 
#———————————————————————————————————————————————————————————————————————————————————————————————————
 
when isMainModule:
for sec in [7259, 86400, 6000000]:
echo sec, "s = ", $$sec</lang>
 
{{out}}
 
Output is the same.
 
=={{header|OCaml}}==
Anonymous user