Convert seconds to compound duration: Difference between revisions

m
syntax highlighting fixup automation
(Added XPL0 example.)
m (syntax highlighting fixup automation)
Line 74:
=={{header|11l}}==
{{trans|Julia}}
<langsyntaxhighlight lang="11l">F duration(=sec)
[Int] t
L(dm) [60, 60, 24, 7]
Line 85:
print(duration(7259))
print(duration(86400))
print(duration(6000000))</langsyntaxhighlight>
 
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
{{libheader|Action! Real Math}}
<langsyntaxhighlight Actionlang="action!">INCLUDE "H6:REALMATH.ACT"
DEFINE PTR="CARD"
 
Line 154:
Test("6000000")
RETURN
</syntaxhighlight>
</lang>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Convert_seconds_to_compound_duration.png Screenshot from Atari 8-bit computer]
Line 164:
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
 
procedure Convert is
Line 207:
IO.New_Line;
end loop;
end Convert;</langsyntaxhighlight>
 
{{out}}
Line 222:
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68"># MODE to hold the compound duration #
MODE DURATION = STRUCT( INT weeks, days, hours, minutes, seconds );
 
Line 264:
print( ( TOSTRING TODURATION 7259, newline ) );
print( ( TOSTRING TODURATION 86400, newline ) );
print( ( TOSTRING TODURATION 6000000, newline ) )</langsyntaxhighlight>
{{out}}
<pre>
Line 274:
=={{header|ALGOL W}}==
Based on Algol 68 but Algol W does not have dynamic string handling which makes this more complex.
<langsyntaxhighlight lang="algolw">begin
% record structure to hold a compound duration %
record Duration ( integer weeks, days, hours, minutes, seconds );
Line 360:
write( durationToString( toDuration( 86400 ) ) );
write( durationToString( toDuration( 6000000 ) ) )
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 370:
=={{header|APL}}==
{{works with|Dyalog APL}}
<langsyntaxhighlight APLlang="apl">duration←{
names←'wk' 'd' 'hr' 'min' 'sec'
parts←0 7 24 60 60⊤⍵
fmt←⍕¨(parts≠0)/parts,¨names
¯2↓∊fmt,¨⊂', '
}</langsyntaxhighlight>
{{out}}
<pre> duration 7259
Line 386:
=={{header|AppleScript}}==
 
<syntaxhighlight lang="applescript">
<lang AppleScript>
-------------------- COMPOUND DURATIONS ------------------
 
Line 538:
end repeat
return zs
end zip</langsyntaxhighlight>
{{Out}}
<pre>7259 -> 2 hr, 59 sec
Line 548:
A more straightforward solution:
 
<langsyntaxhighlight lang="applescript">on secondsToCompoundDuration(s)
if ((s's class is not integer) or (s < 0)) then
error "secondsToCompoundDuration() handler only accepts positive integers."
Line 587:
return secondsToCompoundDuration(7259) & linefeed & ¬
secondsToCompoundDuration(86400) & linefeed & ¬
secondsToCompoundDuration(6000000)</langsyntaxhighlight>
 
{{output}}
Line 595:
 
=={{header|Applesoft BASIC}}==
<langsyntaxhighlight ApplesoftBasiclang="applesoftbasic">100 DATA604800,WK,86400,D,3600,HR,60,MIN,1,SEC
110 FOR I = 0 TO 4
120 READ M(I), U$(I)
Line 615:
 
270 END
</syntaxhighlight>
</lang>
 
=={{header|Arturo}}==
{{trans|Nim}}
<langsyntaxhighlight lang="rebol">Units: [" wk", " d", " hr", " min", " sec"]
Quantities: @[7 * 24 * 60 * 60, 24 * 60 * 60, 60 * 60, 60, 1]
Line 639:
loop [7259 86400 6000000] 't [
print [t "s => " durationString t]
]</langsyntaxhighlight>
 
{{out}}
Line 648:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">duration(n){
sec:=1, min:=60*sec, hr:=60*min, day:=24*hr, wk:=7*day
w :=n//wk , n:=Mod(n,wk)
Line 656:
s :=n
return trim((w?w " wk, ":"") (d?d " d, ":"") (h?h " hr, ":"") (m?m " min, ":"") (s?s " sec":""),", ")
}</langsyntaxhighlight>
Examples:<langsyntaxhighlight AutoHotkeylang="autohotkey">data=
(
7259
Line 667:
res .= A_LoopField "`t: " duration(A_LoopField) "`n"
MsgBox % res
return</langsyntaxhighlight>
Outputs:<pre>7259 : 2 hr, 59 sec
86400 : 1 d
Line 673:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f CONVERT_SECONDS_TO_COMPOUND_DURATION.AWK
BEGIN {
Line 708:
return(str)
}
</syntaxhighlight>
</lang>
<p>Output:</p>
<pre>
Line 726:
 
==={{header|Commodore BASIC}}===
<langsyntaxhighlight lang="gwbasic">10 REM CONVERT SECONDS TO COMPOUND DURATION
20 REM ADAPTED FROM RUN BASIC VERSION
30 REM ===============================================================
Line 760:
1190 PRINT SC;"SEC"
1200 PRINT
1210 RETURN</langsyntaxhighlight>
{{out}}
7259 sec
Line 772:
 
==={{header|BaCon}}===
<langsyntaxhighlight lang="freebasic">
'--- SAY_TIME Convert seconds to compound duration
'--- Weeks, days hours, minutes ,seconds
Line 811:
'---result 9 wk, 6 d, 10 h, 40 min, 7 sec
SAY_TIME(6000007)
</langsyntaxhighlight>
==={{header|BBC BASIC}}===
<langsyntaxhighlight lang="bbcbasic">REM >compduration
PRINT FN_convert(7259)
PRINT FN_convert(86400)
Line 835:
ENDIF
NEXT
= compound$</langsyntaxhighlight>
{{out}}
<pre>2 hr, 59 sec
Line 842:
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "Seconds.bas"
110 NUMERIC UN(1 TO 5),SEC,UNIT
120 STRING T$(1 TO 5)*3
Line 856:
220 END IF
230 NEXT
240 PRINT</langsyntaxhighlight>
 
=={{header|Batch File}}==
<langsyntaxhighlight lang="dos">@echo off
::The Main Thing...
for %%d in (7259 86400 6000000) do call :duration %%d
Line 884:
if %1 gtr 0 echo %1 sec = %output:~1,-1%
goto :EOF
::/The Function.</langsyntaxhighlight>
{{Out}}
<pre>
Line 894:
=={{header|beeswax}}==
 
<langsyntaxhighlight lang="beeswax">#>%f# #>%f# #f%<##>%f#
pq":X~7~ :X@~++8~8@:X:X@~-~4~.+~8@T_
## ## #### #`K0[`}`D2[`}BF3< <
>{` wk, `>g?"p{` d, `>g?"p{` hr, `>g?"p{` min, `>g"b{` sec, `b
> d > d > d > d</langsyntaxhighlight>
 
{{Out}}
Line 921:
The value to convert is read from stdin, and the corresponding compound duration is written to stdout.
 
<langsyntaxhighlight lang="befunge">&>:"<"%\"O{rq"**+\"<"/:"<"%\"r<|":*+*5-\v
v-7*"l~"/7\"d"\%7:/*83\+*:"xD"\%*83:/"<"<
> \:! #v_v#-#<",",#$48*#<,#<.#<>#_:"~"%,v
^_@#:$$< > .02g92p ^ ^!:/"~"<</langsyntaxhighlight>
 
{{out}}
Line 937:
 
===C: Version written in C89. Average skill level.===
<langsyntaxhighlight lang="c">/*
* Program seconds2string, C89 version.
*
Line 999:
 
return EXIT_FAILURE;
}</langsyntaxhighlight>
 
===C: Version written in C99. Low skill level.===
<syntaxhighlight lang="c">
<lang c>
#include <inttypes.h> /* requires c99 */
#include <stdbool.h> /* requires c99 */
Line 1,143:
return minutes*60;
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,160:
 
===C#: Standard method===
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 1,211:
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,227:
{{libheader|System.Linq}}
{{works with|C sharp|6}}
<langsyntaxhighlight lang="csharp">private static string ConvertToCompoundDuration(int seconds)
{
if (seconds < 0) throw new ArgumentOutOfRangeException(nameof(seconds));
Line 1,240:
where parts[index] > 0
select parts[index] + units[index]);
}</langsyntaxhighlight>
 
=={{header|C++}}==
{{works with|C++11}}
<langsyntaxhighlight lang="cpp">
#include <iostream>
#include <vector>
Line 1,280:
std::cout << " 86400 sec is "; print(convert( 86400));
std::cout << "6000000 sec is "; print(convert(6000000));
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,289:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(require '[clojure.string :as string])
 
(def seconds-in-minute 60)
Line 1,316:
(seconds->duration 7259)
(seconds->duration 86400)
(seconds->duration 6000000)</langsyntaxhighlight>
 
{{out}}
Line 1,326:
 
=={{header|CLU}}==
<langsyntaxhighlight lang="clu">duration = proc (s: int) returns (string)
own units: array[string] := array[string]$["wk","d","hr","min","sec"]
own sizes: array[int] := array[int]$[2:7,24,60,60]
Line 1,353:
stream$putl(po, int$unparse(test) || " => " || duration(test))
end
end start_up</langsyntaxhighlight>
{{out}}
<pre>7259 => 2 hr, 59 sec
Line 1,360:
 
=={{header|COBOL}}==
<langsyntaxhighlight COBOLlang="cobol"> identification division.
program-id. fmt-dura.
data division.
Line 1,433:
.
end program fmt.
end program fmt-dura.</langsyntaxhighlight>
<pre>Enter duration (seconds): 7259
2 hr, 59 sec
Line 1,442:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defconstant +seconds-in-minute* 60)
(defconstant +seconds-in-hour* (* 60 +seconds-in-minute*))
(defconstant +seconds-in-day* (* 24 +seconds-in-hour*))
Line 1,463:
(seconds->duration 86400)
(seconds->duration 6000000)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,472:
 
=={{header|D}}==
<syntaxhighlight lang="d">
<lang d>
import std.stdio, std.conv, std.algorithm;
 
Line 1,512:
6_000_000.ConvertSeconds.writeln;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,521:
 
=={{header|EasyLang}}==
<syntaxhighlight lang="text">func split sec . s$ .
divs[] = [ 60 60 24 7 ]
n$[] = [ "sec" "min" "hr" "d" "wk" ]
Line 1,545:
print s$
call split 6000000 s$
print s$</langsyntaxhighlight>
 
{{out}}
Line 1,555:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Convert do
@minute 60
@hour @minute*60
Line 1,575:
Enum.each([7259, 86400, 6000000], fn sec ->
:io.fwrite "~10w sec : ~s~n", [sec, Convert.sec_to_str(sec)]
end)</langsyntaxhighlight>
 
{{out}}
Line 1,591:
Function ''intercalate/2'' is copied from [https://github.com/tim/erlang-oauth/blob/master/src/oauth.erl a Tim Fletcher's GitHub repository].
 
<langsyntaxhighlight lang="erlang">
-module(convert_seconds).
 
Line 1,681:
 
% **************************************************
</syntaxhighlight>
</lang>
 
Output:
Line 1,691:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">open System
 
let convert seconds =
Line 1,711:
|> Seq.map (fun str -> let sec = UInt32.Parse str in (sec, convert sec))
|> Seq.iter (fun (s, v) -> printfn "%10i = %s" s v)
0</langsyntaxhighlight>
{{out}}
<pre>>RosettaCode 7259 86400 6000000
Line 1,719:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: assocs io kernel math math.parser qw sequences
sequences.generalizations ;
 
Line 1,731:
[ first "0" = ] reject [ " " join ] map ", " join print ;
7259 86400 6000000 [ .time ] tri@</langsyntaxhighlight>
{{out}}
<pre>
Line 1,741:
=={{header|Forth}}==
{{works with|Gforth|0.7.3}}
<langsyntaxhighlight Forthlang="forth">CREATE C 0 ,
: ., C @ IF ." , " THEN 1 C ! ;
: .TIME ( n --)
Line 1,748:
[ 60 60 * ]L /MOD ?DUP-IF ., . ." hr" THEN
[ 60 ]L /MOD ?DUP-IF ., . ." min" THEN
?DUP-IF ., . ." sec" THEN 0 C ! ;</langsyntaxhighlight>
{{out}}
<pre>2 hr, 59 sec
Line 1,758:
 
If the time to describe was not an integer but a floating-point value with fractional parts, then there is a complication. The number of seconds can be less than sixty, but, on output, 60 seconds can appear. If the number of seconds was to be written with one decimal digit (say) and the output format was F4.1 for that, then if the value was 59·95 or more, it will be rounded up for output, in this example to 60·0. Various systems make this mistake, as also with latitude and longitude, and it is a general problem. A fixup pass is necessary before generating the output: maintain an array with the integer values of the various units, then (for one decimal digit usage) check that the seconds part is less than 59·95. If not, set it to zero and augment the minutes count. If this is 60 or more, set it to zero and augment the hours count, and so on. Thus the array.
<syntaxhighlight lang="fortran">
<lang Fortran>
SUBROUTINE PROUST(T) !Remembrance of time passed.
INTEGER T !The time, in seconds. Positive only, please.
Line 1,796:
CALL PROUST(-666)
END
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,808:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">'FreeBASIC version 1.05 32/64 bit
 
Sub Show(m As Long)
Line 1,844:
Show 86400 seconds
Show 6000000 seconds
sleep</langsyntaxhighlight>
Output:
<pre>
Line 1,855:
Frink's <CODE>-&gt;</CODE> operator can break a unit of measure into its constituent parts. However, it does not suppress zero-valued elements unless they are at the beginning or the end, so we have to do that manually.
 
<langsyntaxhighlight lang="frink">
wk := week
n = eval[input["Enter duration in seconds: "]]
Line 1,861:
res =~ %s/, 0[^,]+//g
println[res]
</syntaxhighlight>
</lang>
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=d7f00b8a96a6f792f0164f622f0686df Click this link to run this code]'''
<langsyntaxhighlight lang="gambas">Public Sub Main()
Dim iInput As Integer[] = [7259, 86400, 6000000] 'Input details
Dim iChecks As Integer[] = [604800, 86400, 3600, 60] 'Weeks, days, hours, mins in seconds
Line 1,895:
Next
 
End</langsyntaxhighlight>
Output:
<pre>
Line 1,904:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,953:
return
}
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,962:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Control.Monad (forM_)
import Data.List (intercalate, mapAccumR)
import System.Environment (getArgs)
Line 1,989:
forM_ args $ \arg -> case readMaybe arg of
Just n -> printf "%7d seconds = %s\n" n (compoundDuration n)
Nothing -> putStrLn $ "Invalid number of seconds: " ++ arg</langsyntaxhighlight>
 
{{out}}
Line 2,001:
Or, parameterising both the local names for these durations, and also the working assumptions about hours per day, and days per week:
 
<langsyntaxhighlight lang="haskell">import Data.List (intercalate, mapAccumR)
 
---------------- COMPOUND DURATION STRINGS ---------------
Line 2,071:
 
putStrLn "\nor, at 8 hours per day, 5 days per week:"
mapM_ (putStrLn . translation names 5 8) tests</langsyntaxhighlight>
{{Out}}
<pre>Assuming 24/7:
Line 2,087:
Implementation:
 
<langsyntaxhighlight Jlang="j">fmtsecs=: verb define
seq=. 0 7 24 60 60 #: y
}: ;:inv ,(0 ~: seq) # (8!:0 seq) ,. <;.2'wk,d,hr,min,sec,'
)</langsyntaxhighlight>
 
The first line uses integer division with remainder to break the value in seconds into its components (weeks, days, hours, minutes, seconds).
Line 2,098:
Task examples:
 
<langsyntaxhighlight Jlang="j"> fmtsecs 7259
2 hr, 59 sec
fmtsecs 86400
1 d
fmtsecs 6000000
9 wk, 6 d, 10 hr, 40 min</langsyntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">public class CompoundDuration {
 
public static void main(String[] args) {
Line 2,136:
return sec;
}
}</langsyntaxhighlight>
 
<pre>2 hr, 59 sec
Line 2,148:
====ES5====
 
<langsyntaxhighlight JavaScriptlang="javascript">(function () {
'use strict';
 
Line 2,207:
 
})();
</syntaxhighlight>
</lang>
 
{{Out}}
Line 2,216:
 
====ES6====
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
"use strict";
 
Line 2,263:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>7259 -> 2 hr, 59 sec
Line 2,271:
=={{header|jq}}==
{{works with|jq|1.4}}
<langsyntaxhighlight lang="jq">def seconds_to_time_string:
def nonzero(text): floor | if . > 0 then "\(.) \(text)" else empty end;
if . == 0 then "0 sec"
Line 2,281:
(. % 60 | nonzero("sec"))]
| join(", ")
end;</langsyntaxhighlight>
 
''Examples''':
<langsyntaxhighlight lang="jq">0, 7259, 86400, 6000000 | "\(.): \(seconds_to_time_string)"</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="sh">$ jq -r -n -f Convert_seconds_to_compound_duration.jq
0: 0 sec
7259: 2 hr, 59 sec
86400: 1 d
6000000: 9 wk, 6 d, 10 hr, 40 min</langsyntaxhighlight>
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia"># 1.x
function duration(sec::Integer)::String
t = Array{Int}([])
Line 2,307:
@show duration(86400)
@show duration(6000000)
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,317:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">fun compoundDuration(n: Int): String {
if (n < 0) return "" // task doesn't ask for negative integers to be converted
if (n == 0) return "0 sec"
Line 2,355:
val durations = intArrayOf(0, 7, 84, 7259, 86400, 6000000)
durations.forEach { println("$it\t-> ${compoundDuration(it)}") }
}</langsyntaxhighlight>
 
{{out}}
Line 2,369:
=={{header|Liberty BASIC}}==
I got a bit carried away and added 'years'...
<syntaxhighlight lang="lb">
<lang lb>
[start]
input "Enter SECONDS: "; seconds
Line 2,458:
print
goto [start]
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,474:
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">function duration (secs)
local units, dur = {"wk", "d", "hr", "min"}, ""
for i, v in ipairs({604800, 86400, 3600, 60}) do
Line 2,491:
print(duration(7259))
print(duration(86400))
print(duration(6000000))</langsyntaxhighlight>
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">
<lang Maple>
tim := proc (s) local weeks, days, hours, minutes, seconds;
weeks := trunc((1/604800)*s);
Line 2,503:
printf("%s", cat(`if`(0 < weeks, cat(weeks, "wk, "), NULL), `if`(0 < days, cat(days, "d, "), NULL), `if`(0 < hours, cat(hours, "hr, "), NULL), `if`(0 < minutes, cat(minutes, "min, "), NULL), `if`(0 < seconds, cat(seconds, "sec"), NULL)))
end proc;
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">compoundDuration[x_Integer] :=
StringJoin @@ (Riffle[
ToString /@ ((({Floor[x/604800],
Line 2,517:
Grid[Table[{n, "secs =",
compoundDuration[n]}, {n, {7259, 86400, 6000000}}],
Alignment -> {Left, Baseline}]</langsyntaxhighlight>
 
{{out}}
Line 2,525:
 
=={{header|Nim}}==
<langsyntaxhighlight Nimlang="nim">from strutils import addSep
 
const
Line 2,552:
when isMainModule:
for sec in [7259, 86400, 6000000]:
echo sec, "s = ", $$sec</langsyntaxhighlight>
 
{{out}}
Line 2,563:
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).
 
<langsyntaxhighlight Nimlang="nim">import times
from algorithm import reversed
from strutils import addSep
Line 2,589:
when isMainModule:
for sec in [7259, 86400, 6000000]:
echo sec, "s = ", $$sec</langsyntaxhighlight>
 
{{out}}
Line 2,597:
=={{header|OCaml}}==
{{works with|OCaml|4.03+}}
<langsyntaxhighlight lang="ocaml">let divisors = [
(max_int, "wk"); (* many wk = many wk *)
(7, "d"); (* 7 d = 1 wk *)
Line 2,668:
n calc s
in
List.iter testit test_cases</langsyntaxhighlight>
{{out}}
[PASS] 7259 seconds -> 2 hr, 59 sec; expected: 2 hr, 59 sec
Line 2,683:
{{Works with|PARI/GP|2.7.4 and above}}
 
<langsyntaxhighlight lang="parigp">
\\ Convert seconds to compound duration
\\ 4/11/16 aev
Line 2,700:
print(secs2compdur(6000000));
}
</langsyntaxhighlight>
 
{{Output}}
Line 2,712:
=={{header|Pascal}}==
{{works with|Extended Pascal}}
<langsyntaxhighlight lang="pascal">program convertSecondsToCompoundDuration(output);
 
const
Line 2,826:
writeLn( 86400, ' seconds are “', timeSpanString(86400), '”');
writeLn(6000000, ' seconds are “', timeSpanString(6000000), '”')
end.</langsyntaxhighlight>
{{out}}
7259 seconds are “2 hr, 59 sec”
Line 2,835:
 
===Direct calculation===
<langsyntaxhighlight lang="perl">use strict;
use warnings;
 
Line 2,852:
for (7259, 86400, 6000000) {
printf "%7d sec = %s\n", $_, compound_duration($_)
}</langsyntaxhighlight>
{{out}}
<pre> 7259 sec = 2 hr, 59 sec
Line 2,860:
===Using polymod===
More general approach for mixed-radix conversions.
<langsyntaxhighlight lang="perl">use strict;
use warnings;
use Math::AnyNum 'polymod';
Line 2,878:
for (<7259 86400 6000000 3380521>) {
printf "%7d sec = %s\n", $_, compound_duration($_)
}</langsyntaxhighlight>
{{out}}
<pre> 7259 sec = 2 hr, 59 sec
Line 2,887:
=={{header|Phix}}==
There is a standard function for this, for more details see builtins/pelapsed.e (which will be kept up to date, unlike having a copy here)
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">elapsed</span><span style="color: #0000FF;">(</span><span style="color: #000000;">7259</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">elapsed</span><span style="color: #0000FF;">(</span><span style="color: #000000;">86400</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">elapsed</span><span style="color: #0000FF;">(</span><span style="color: #000000;">6000000</span><span style="color: #0000FF;">)</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,900:
</pre>
You may also be interested in the timedelta() function, which converts durations to seconds, eg:
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">include</span> <span style="color: #004080;">timedate</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">elapsed</span><span style="color: #0000FF;">(</span><span style="color: #000000;">6000000</span><span style="color: #0000FF;">-</span><span style="color: #7060A8;">timedelta</span><span style="color: #0000FF;">(</span><span style="color: #000000;">days</span><span style="color: #0000FF;">:=</span><span style="color: #000000;">6</span><span style="color: #0000FF;">,</span><span style="color: #000000;">hours</span><span style="color: #0000FF;">:=</span><span style="color: #000000;">10</span><span style="color: #0000FF;">))</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,911:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(for Sec (7259 86400 6000000)
(tab (-10 -30)
Sec
Line 2,921:
(pack @ " " Str) ) )
(604800 86400 3600 60 1)
'("wk" "d" "hr" "min" "sec") ) ) ) )</langsyntaxhighlight>
Output:
<pre>7259 2 hr, 59 sec
Line 2,928:
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
/* Convert seconds to Compound Duration (weeks, days, hours, minutes, seconds). */
 
Line 2,956:
end;
end cvt;
</syntaxhighlight>
</lang>
Results:
<pre>
Line 2,972:
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Get-Time
{
Line 3,089:
}
}
</syntaxhighlight>
</lang>
 
{{Out}}
Line 3,127:
See below for examples.
 
<langsyntaxhighlight lang="prolog">:- use_module(library(clpfd)).
 
% helper to perform the operation with just a number.
Line 3,170:
time_type(hr, 60 * 60).
time_type(min, 60).
time_type(sec, 1).</langsyntaxhighlight>
 
{{out}}
Line 3,185:
 
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">
<lang PureBasic>
EnableExplicit
 
Line 3,241:
CloseConsole()
EndIf
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,253:
 
===Python: Procedural===
<langsyntaxhighlight lang="python">>>> def duration(seconds):
t= []
for dm in (60, 60, 24, 7):
Line 3,270:
86400 sec = 1 d
6000000 sec = 9 wk, 6 d, 10 hr, 40 min
>>> </langsyntaxhighlight>
 
===Python: Functional===
<langsyntaxhighlight lang="python">>>> def duration(seconds, _maxweeks=99999999999):
return ', '.join('%d %s' % (num, unit)
for num, unit in zip([(seconds // d) % m
Line 3,289:
86400 sec = 1 d
6000000 sec = 9 wk, 6 d, 10 hr, 40 min
>>> </langsyntaxhighlight>
 
Or, composing a solution from pure curried functions, including the '''mapAccumR''' abstraction (a combination of of '''map''' and '''reduce''', implemented in a variety of languages and functional libraries, in which a new list is derived by repeated application of the same function, as an accumulator (here, a remainder) passes from right to left):
 
<langsyntaxhighlight lang="python">'''Compound duration'''
 
from functools import reduce
Line 3,379:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Compound durations from numbers of seconds:
Line 3,389:
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> [ ' [ 60 60 24 7 ]
witheach [ /mod swap ]
$ ""
Line 3,407:
say " seconds is "
duration$ echo$
say "." cr ]</langsyntaxhighlight>
 
{{Out}}
Line 3,419:
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">#lang racket/base
(require racket/string
racket/list)
Line 3,450:
(check-equal? (seconds->compound-duration-string 6000000) "9 wk, 6 d, 10 hr, 40 min"))
 
;; Tim Brown 2015-07-21</langsyntaxhighlight>
 
{{out}}
Line 3,460:
The built-in <code>polymod</code> method (which is a generalization of the <code>divmod</code> function known from other languages), is a perfect match for a task like this:
 
<syntaxhighlight lang="raku" perl6line>sub compound-duration ($seconds) {
($seconds.polymod(60, 60, 24, 7) Z <sec min hr d wk>)
.grep(*[0]).reverse.join(", ")
Line 3,469:
for 7259, 86400, 6000000 {
say "{.fmt: '%7d'} sec = {compound-duration $_}";
}</langsyntaxhighlight>
 
{{out}}
Line 3,480:
=={{header|REXX}}==
===version 1===
<langsyntaxhighlight lang="rexx">/* REXX ---------------------------------------------------------------
* Format seconds into a time string
*--------------------------------------------------------------------*/
Line 3,525:
a=what%how
b=what//how
Return a b</langsyntaxhighlight>
{{out}}
<pre>2 hr, 59 sec
Line 3,536:
===version 2===
This REXX version can also handle fractional (seconds) as well as values of zero (time units).
<langsyntaxhighlight lang="rexx">/*rexx program demonstrates how to convert a number of seconds to bigger time units.*/
parse arg @; if @='' then @=7259 86400 6000000 /*Not specified? Then use the default.*/
 
Line 3,554:
return $
/*──────────────────────────────────────────────────────────────────────────────────────*/
timeU: parse arg u,$; _= x%u; if _==0 then return ''; x= x - _*u; return _ $","</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default (internal) inputs:}}
<pre>
Line 3,570:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
sec = 6000005
week = floor(sec/60/60/24/7)
Line 3,587:
if second > 0 see second
see " seconds" + nl ok
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">MINUTE = 60
HOUR = MINUTE*60
DAY = HOUR*24
Line 3,604:
end
 
[7259, 86400, 6000000].each{|t| puts "#{t}\t: #{sec_to_str(t)}"}</langsyntaxhighlight>
Output:
<pre>
Line 3,613:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">sec = 6000005
week = int(sec/60/60/24/7)
day = int(sec/60/60/24) mod 7
Line 3,625:
if hour > 0 then print hour;" hours ";
if minute > 0 then print minute;" minutes ";
if second > 0 then print second;" seconds"</langsyntaxhighlight>
 
=={{header|Rust}}==
This solution deviates from the prompt a bit in order to make it more general. The benefit of doing it this way is that any values can be filled in for days, hours, minutes and seconds and the `balance` method will do the balancing accordingly. Also, rather than converting the value into a String, it simply implements the `Display` trait.
<langsyntaxhighlight lang="rust">use std::fmt;
 
 
Line 3,674:
ct.balance();
println!("After: {}", ct);
}</langsyntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">//Converting Seconds to Compound Duration
 
object seconds{
Line 3,705:
println("Second = " + sec)
}
}</langsyntaxhighlight>
 
=={{header|Scheme}}==
Line 3,713:
This version uses delete from SRFI 1 and string-join from SRFI 13:
 
<langsyntaxhighlight lang="scheme">
(import (scheme base)
(scheme write)
Line 3,742:
(display (seconds->duration 86400)) (newline)
(display (seconds->duration 6000000)) (newline)
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,753:
=={{header|Sidef}}==
{{trans|Raku}}
<langsyntaxhighlight lang="ruby">func polymod(n, *divs) {
gather {
divs.each { |i|
Line 3,771:
[7259, 86400, 6000000].each { |s|
say "#{'%7d' % s} sec = #{compound_duration(s)}"
}</langsyntaxhighlight>
 
{{out}}
Line 3,781:
 
=={{header|Standard ML}}==
<langsyntaxhighlight lang="sml">local
fun fmtNonZero (0, _, list) = list
| fmtNonZero (n, s, list) = Int.toString n ^ " " ^ s :: list
Line 3,796:
end
 
val () = app (fn s => print (compoundDuration s ^ "\n")) [7259, 86400, 6000000]</langsyntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">func duration (_ secs:Int) -> String {
if secs <= 0 { return "" }
let units = [(604800,"wk"), (86400,"d"), (3600,"hr"), (60,"min")]
Line 3,820:
print(duration(7259))
print(duration(86400))
print(duration(6000000))</langsyntaxhighlight>
 
=={{header|Tcl}}==
Line 3,826:
The data-driven procedure below can be customised to use different breakpoints, simply by editing the dictionary.
 
<langsyntaxhighlight Tcllang="tcl">proc sec2str {i} {
set factors {
sec 60
Line 3,863:
check {sec2str 7259} {2 hr, 59 sec}
check {sec2str 86400} {1 d}
check {sec2str 6000000} {9 wk, 6 d, 10 hr, 40 min}</langsyntaxhighlight>
 
{{Out}}
Line 3,872:
=={{header|uBasic/4tH}}==
Since uBasic/4tH is integer-only, it is hard to return a string. However, it is capable to transform an integer value as required.
<syntaxhighlight lang="text">Proc _CompoundDuration(7259)
Proc _CompoundDuration(86400)
Proc _CompoundDuration(6000000)
Line 3,910:
_d Print " d"; : Return
_hr Print " hr"; : Return
_min Print " min"; : Return</langsyntaxhighlight>
{{out}}
<pre>2 hr, 59 sec
Line 3,919:
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Private Function compound_duration(ByVal seconds As Long) As String
minutes = 60
hours = 60 * minutes
Line 3,949:
Debug.Print compound_duration(86400)
Debug.Print compound_duration(6000000)
End Sub</langsyntaxhighlight>{{out}}
<pre>2 hr, 59 sec
1 d
Line 3,955:
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
Function compound_duration(n)
Do Until n = 0
Line 3,993:
WScript.StdOut.WriteLine compound_duration(86400)
WScript.StdOut.WriteLine compound_duration(6000000)
</syntaxhighlight>
</lang>
 
{{Out}}
Line 4,003:
 
=={{header|Wren}}==
<langsyntaxhighlight lang="ecmascript">var duration = Fn.new { |s|
if (s < 1) return "0 sec"
var dur = ""
Line 4,021:
}
 
for (s in [7259, 86400, 6000000]) System.print(duration.call(s))</langsyntaxhighlight>
 
{{out}}
Line 4,031:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">char Str(80);
func Duration(Sec); \Convert seconds to compound duration
int Sec, Amt, Unit, DoComma, I, Quot;
Line 4,058:
Text(0, Duration(86400));
Text(0, Duration(6_000_000));
]</langsyntaxhighlight>
 
{{out}}
Line 4,068:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn toWDHMS(sec){ //-->(wk,d,h,m,s)
r,b:=List(),0;
foreach u in (T(60,60,24,7)){
Line 4,075:
}
r.append(sec).reverse()
}</langsyntaxhighlight>
Or, if you like to be concise:
<langsyntaxhighlight lang="zkl">fcn toWDHMS(sec){ //-->(wk,d,h,m,s)
T(60,60,24,7).reduce(fcn(n,u,r){ n,u=n.divr(u); r.append(u); n },
sec,r:=List()):r.append(_).reverse();
}</langsyntaxhighlight>
were the ":" op takes the left result and stuffs it into the "_" position.
<langsyntaxhighlight lang="zkl">units:=T(" wk"," d"," hr"," min"," sec");
foreach s in (T(7259,86400,6000000)){
toWDHMS(s).zip(units).pump(List,fcn([(t,u)]){ t and String(t,u) or "" })
.filter().concat(", ").println();
}</langsyntaxhighlight>
{{out}}
<pre>
Line 4,096:
=={{header|ZX Spectrum Basic}}==
{{trans|AWK}}
<langsyntaxhighlight lang="zxbasic">10 LET m=60: LET h=60*m: LET d=h*24: LET w=d*7
20 DATA 10,7259,86400,6000000,0,1,60,3600,604799,604800,694861
30 READ n
Line 4,117:
200 NEXT i
210 STOP
220 DEF FN m(a,b)=a-INT (a/b)*b</langsyntaxhighlight>
10,327

edits