Convert seconds to compound duration: Difference between revisions

Content added Content deleted
(Added XPL0 example.)
m (syntax highlighting fixup automation)
Line 74: Line 74:
=={{header|11l}}==
=={{header|11l}}==
{{trans|Julia}}
{{trans|Julia}}
<lang 11l>F duration(=sec)
<syntaxhighlight lang="11l">F duration(=sec)
[Int] t
[Int] t
L(dm) [60, 60, 24, 7]
L(dm) [60, 60, 24, 7]
Line 85: Line 85:
print(duration(7259))
print(duration(7259))
print(duration(86400))
print(duration(86400))
print(duration(6000000))</lang>
print(duration(6000000))</syntaxhighlight>


=={{header|Action!}}==
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
{{libheader|Action! Tool Kit}}
{{libheader|Action! Real Math}}
{{libheader|Action! Real Math}}
<lang Action!>INCLUDE "H6:REALMATH.ACT"
<syntaxhighlight lang="action!">INCLUDE "H6:REALMATH.ACT"
DEFINE PTR="CARD"
DEFINE PTR="CARD"


Line 154: Line 154:
Test("6000000")
Test("6000000")
RETURN
RETURN
</syntaxhighlight>
</lang>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Convert_seconds_to_compound_duration.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Convert_seconds_to_compound_duration.png Screenshot from Atari 8-bit computer]
Line 164: Line 164:


=={{header|Ada}}==
=={{header|Ada}}==
<lang Ada>with Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO;


procedure Convert is
procedure Convert is
Line 207: Line 207:
IO.New_Line;
IO.New_Line;
end loop;
end loop;
end Convert;</lang>
end Convert;</syntaxhighlight>


{{out}}
{{out}}
Line 222: Line 222:


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
<lang algol68># MODE to hold the compound duration #
<syntaxhighlight lang="algol68"># MODE to hold the compound duration #
MODE DURATION = STRUCT( INT weeks, days, hours, minutes, seconds );
MODE DURATION = STRUCT( INT weeks, days, hours, minutes, seconds );


Line 264: Line 264:
print( ( TOSTRING TODURATION 7259, newline ) );
print( ( TOSTRING TODURATION 7259, newline ) );
print( ( TOSTRING TODURATION 86400, newline ) );
print( ( TOSTRING TODURATION 86400, newline ) );
print( ( TOSTRING TODURATION 6000000, newline ) )</lang>
print( ( TOSTRING TODURATION 6000000, newline ) )</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 274: Line 274:
=={{header|ALGOL W}}==
=={{header|ALGOL W}}==
Based on Algol 68 but Algol W does not have dynamic string handling which makes this more complex.
Based on Algol 68 but Algol W does not have dynamic string handling which makes this more complex.
<lang algolw>begin
<syntaxhighlight lang="algolw">begin
% record structure to hold a compound duration %
% record structure to hold a compound duration %
record Duration ( integer weeks, days, hours, minutes, seconds );
record Duration ( integer weeks, days, hours, minutes, seconds );
Line 360: Line 360:
write( durationToString( toDuration( 86400 ) ) );
write( durationToString( toDuration( 86400 ) ) );
write( durationToString( toDuration( 6000000 ) ) )
write( durationToString( toDuration( 6000000 ) ) )
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 370: Line 370:
=={{header|APL}}==
=={{header|APL}}==
{{works with|Dyalog APL}}
{{works with|Dyalog APL}}
<lang APL>duration←{
<syntaxhighlight lang="apl">duration←{
names←'wk' 'd' 'hr' 'min' 'sec'
names←'wk' 'd' 'hr' 'min' 'sec'
parts←0 7 24 60 60⊤⍵
parts←0 7 24 60 60⊤⍵
fmt←⍕¨(parts≠0)/parts,¨names
fmt←⍕¨(parts≠0)/parts,¨names
¯2↓∊fmt,¨⊂', '
¯2↓∊fmt,¨⊂', '
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre> duration 7259
<pre> duration 7259
Line 386: Line 386:
=={{header|AppleScript}}==
=={{header|AppleScript}}==


<syntaxhighlight lang="applescript">
<lang AppleScript>
-------------------- COMPOUND DURATIONS ------------------
-------------------- COMPOUND DURATIONS ------------------


Line 538: Line 538:
end repeat
end repeat
return zs
return zs
end zip</lang>
end zip</syntaxhighlight>
{{Out}}
{{Out}}
<pre>7259 -> 2 hr, 59 sec
<pre>7259 -> 2 hr, 59 sec
Line 548: Line 548:
A more straightforward solution:
A more straightforward solution:


<lang applescript>on secondsToCompoundDuration(s)
<syntaxhighlight lang="applescript">on secondsToCompoundDuration(s)
if ((s's class is not integer) or (s < 0)) then
if ((s's class is not integer) or (s < 0)) then
error "secondsToCompoundDuration() handler only accepts positive integers."
error "secondsToCompoundDuration() handler only accepts positive integers."
Line 587: Line 587:
return secondsToCompoundDuration(7259) & linefeed & ¬
return secondsToCompoundDuration(7259) & linefeed & ¬
secondsToCompoundDuration(86400) & linefeed & ¬
secondsToCompoundDuration(86400) & linefeed & ¬
secondsToCompoundDuration(6000000)</lang>
secondsToCompoundDuration(6000000)</syntaxhighlight>


{{output}}
{{output}}
Line 595: Line 595:


=={{header|Applesoft BASIC}}==
=={{header|Applesoft BASIC}}==
<lang ApplesoftBasic>100 DATA604800,WK,86400,D,3600,HR,60,MIN,1,SEC
<syntaxhighlight lang="applesoftbasic">100 DATA604800,WK,86400,D,3600,HR,60,MIN,1,SEC
110 FOR I = 0 TO 4
110 FOR I = 0 TO 4
120 READ M(I), U$(I)
120 READ M(I), U$(I)
Line 615: Line 615:


270 END
270 END
</syntaxhighlight>
</lang>


=={{header|Arturo}}==
=={{header|Arturo}}==
{{trans|Nim}}
{{trans|Nim}}
<lang rebol>Units: [" wk", " d", " hr", " min", " sec"]
<syntaxhighlight lang="rebol">Units: [" wk", " d", " hr", " min", " sec"]
Quantities: @[7 * 24 * 60 * 60, 24 * 60 * 60, 60 * 60, 60, 1]
Quantities: @[7 * 24 * 60 * 60, 24 * 60 * 60, 60 * 60, 60, 1]
Line 639: Line 639:
loop [7259 86400 6000000] 't [
loop [7259 86400 6000000] 't [
print [t "s => " durationString t]
print [t "s => " durationString t]
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 648: Line 648:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>duration(n){
<syntaxhighlight lang="autohotkey">duration(n){
sec:=1, min:=60*sec, hr:=60*min, day:=24*hr, wk:=7*day
sec:=1, min:=60*sec, hr:=60*min, day:=24*hr, wk:=7*day
w :=n//wk , n:=Mod(n,wk)
w :=n//wk , n:=Mod(n,wk)
Line 656: Line 656:
s :=n
s :=n
return trim((w?w " wk, ":"") (d?d " d, ":"") (h?h " hr, ":"") (m?m " min, ":"") (s?s " sec":""),", ")
return trim((w?w " wk, ":"") (d?d " d, ":"") (h?h " hr, ":"") (m?m " min, ":"") (s?s " sec":""),", ")
}</lang>
}</syntaxhighlight>
Examples:<lang AutoHotkey>data=
Examples:<syntaxhighlight lang="autohotkey">data=
(
(
7259
7259
Line 667: Line 667:
res .= A_LoopField "`t: " duration(A_LoopField) "`n"
res .= A_LoopField "`t: " duration(A_LoopField) "`n"
MsgBox % res
MsgBox % res
return</lang>
return</syntaxhighlight>
Outputs:<pre>7259 : 2 hr, 59 sec
Outputs:<pre>7259 : 2 hr, 59 sec
86400 : 1 d
86400 : 1 d
Line 673: Line 673:


=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f CONVERT_SECONDS_TO_COMPOUND_DURATION.AWK
# syntax: GAWK -f CONVERT_SECONDS_TO_COMPOUND_DURATION.AWK
BEGIN {
BEGIN {
Line 708: Line 708:
return(str)
return(str)
}
}
</syntaxhighlight>
</lang>
<p>Output:</p>
<p>Output:</p>
<pre>
<pre>
Line 726: Line 726:


==={{header|Commodore BASIC}}===
==={{header|Commodore BASIC}}===
<lang gwbasic>10 REM CONVERT SECONDS TO COMPOUND DURATION
<syntaxhighlight lang="gwbasic">10 REM CONVERT SECONDS TO COMPOUND DURATION
20 REM ADAPTED FROM RUN BASIC VERSION
20 REM ADAPTED FROM RUN BASIC VERSION
30 REM ===============================================================
30 REM ===============================================================
Line 760: Line 760:
1190 PRINT SC;"SEC"
1190 PRINT SC;"SEC"
1200 PRINT
1200 PRINT
1210 RETURN</lang>
1210 RETURN</syntaxhighlight>
{{out}}
{{out}}
7259 sec
7259 sec
Line 772: Line 772:


==={{header|BaCon}}===
==={{header|BaCon}}===
<lang freebasic>
<syntaxhighlight lang="freebasic">
'--- SAY_TIME Convert seconds to compound duration
'--- SAY_TIME Convert seconds to compound duration
'--- Weeks, days hours, minutes ,seconds
'--- Weeks, days hours, minutes ,seconds
Line 811: Line 811:
'---result 9 wk, 6 d, 10 h, 40 min, 7 sec
'---result 9 wk, 6 d, 10 h, 40 min, 7 sec
SAY_TIME(6000007)
SAY_TIME(6000007)
</lang>
</syntaxhighlight>
==={{header|BBC BASIC}}===
==={{header|BBC BASIC}}===
<lang bbcbasic>REM >compduration
<syntaxhighlight lang="bbcbasic">REM >compduration
PRINT FN_convert(7259)
PRINT FN_convert(7259)
PRINT FN_convert(86400)
PRINT FN_convert(86400)
Line 835: Line 835:
ENDIF
ENDIF
NEXT
NEXT
= compound$</lang>
= compound$</syntaxhighlight>
{{out}}
{{out}}
<pre>2 hr, 59 sec
<pre>2 hr, 59 sec
Line 842: Line 842:


==={{header|IS-BASIC}}===
==={{header|IS-BASIC}}===
<lang IS-BASIC>100 PROGRAM "Seconds.bas"
<syntaxhighlight lang="is-basic">100 PROGRAM "Seconds.bas"
110 NUMERIC UN(1 TO 5),SEC,UNIT
110 NUMERIC UN(1 TO 5),SEC,UNIT
120 STRING T$(1 TO 5)*3
120 STRING T$(1 TO 5)*3
Line 856: Line 856:
220 END IF
220 END IF
230 NEXT
230 NEXT
240 PRINT</lang>
240 PRINT</syntaxhighlight>


=={{header|Batch File}}==
=={{header|Batch File}}==
<lang dos>@echo off
<syntaxhighlight lang="dos">@echo off
::The Main Thing...
::The Main Thing...
for %%d in (7259 86400 6000000) do call :duration %%d
for %%d in (7259 86400 6000000) do call :duration %%d
Line 884: Line 884:
if %1 gtr 0 echo %1 sec = %output:~1,-1%
if %1 gtr 0 echo %1 sec = %output:~1,-1%
goto :EOF
goto :EOF
::/The Function.</lang>
::/The Function.</syntaxhighlight>
{{Out}}
{{Out}}
<pre>
<pre>
Line 894: Line 894:
=={{header|beeswax}}==
=={{header|beeswax}}==


<lang beeswax>#>%f# #>%f# #f%<##>%f#
<syntaxhighlight lang="beeswax">#>%f# #>%f# #f%<##>%f#
pq":X~7~ :X@~++8~8@:X:X@~-~4~.+~8@T_
pq":X~7~ :X@~++8~8@:X:X@~-~4~.+~8@T_
## ## #### #`K0[`}`D2[`}BF3< <
## ## #### #`K0[`}`D2[`}BF3< <
>{` wk, `>g?"p{` d, `>g?"p{` hr, `>g?"p{` min, `>g"b{` sec, `b
>{` wk, `>g?"p{` d, `>g?"p{` hr, `>g?"p{` min, `>g"b{` sec, `b
> d > d > d > d</lang>
> d > d > d > d</syntaxhighlight>


{{Out}}
{{Out}}
Line 921: Line 921:
The value to convert is read from stdin, and the corresponding compound duration is written to stdout.
The value to convert is read from stdin, and the corresponding compound duration is written to stdout.


<lang befunge>&>:"<"%\"O{rq"**+\"<"/:"<"%\"r<|":*+*5-\v
<syntaxhighlight lang="befunge">&>:"<"%\"O{rq"**+\"<"/:"<"%\"r<|":*+*5-\v
v-7*"l~"/7\"d"\%7:/*83\+*:"xD"\%*83:/"<"<
v-7*"l~"/7\"d"\%7:/*83\+*:"xD"\%*83:/"<"<
> \:! #v_v#-#<",",#$48*#<,#<.#<>#_:"~"%,v
> \:! #v_v#-#<",",#$48*#<,#<.#<>#_:"~"%,v
^_@#:$$< > .02g92p ^ ^!:/"~"<</lang>
^_@#:$$< > .02g92p ^ ^!:/"~"<</syntaxhighlight>


{{out}}
{{out}}
Line 937: Line 937:


===C: Version written in C89. Average skill level.===
===C: Version written in C89. Average skill level.===
<lang c>/*
<syntaxhighlight lang="c">/*
* Program seconds2string, C89 version.
* Program seconds2string, C89 version.
*
*
Line 999: Line 999:


return EXIT_FAILURE;
return EXIT_FAILURE;
}</lang>
}</syntaxhighlight>


===C: Version written in C99. Low skill level.===
===C: Version written in C99. Low skill level.===
<syntaxhighlight lang="c">
<lang c>
#include <inttypes.h> /* requires c99 */
#include <inttypes.h> /* requires c99 */
#include <stdbool.h> /* requires c99 */
#include <stdbool.h> /* requires c99 */
Line 1,143: Line 1,143:
return minutes*60;
return minutes*60;
}
}
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,160: Line 1,160:


===C#: Standard method===
===C#: Standard method===
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Linq;
Line 1,211: Line 1,211:
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,227: Line 1,227:
{{libheader|System.Linq}}
{{libheader|System.Linq}}
{{works with|C sharp|6}}
{{works with|C sharp|6}}
<lang csharp>private static string ConvertToCompoundDuration(int seconds)
<syntaxhighlight lang="csharp">private static string ConvertToCompoundDuration(int seconds)
{
{
if (seconds < 0) throw new ArgumentOutOfRangeException(nameof(seconds));
if (seconds < 0) throw new ArgumentOutOfRangeException(nameof(seconds));
Line 1,240: Line 1,240:
where parts[index] > 0
where parts[index] > 0
select parts[index] + units[index]);
select parts[index] + units[index]);
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
{{works with|C++11}}
{{works with|C++11}}
<lang cpp>
<syntaxhighlight lang="cpp">
#include <iostream>
#include <iostream>
#include <vector>
#include <vector>
Line 1,280: Line 1,280:
std::cout << " 86400 sec is "; print(convert( 86400));
std::cout << " 86400 sec is "; print(convert( 86400));
std::cout << "6000000 sec is "; print(convert(6000000));
std::cout << "6000000 sec is "; print(convert(6000000));
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,289: Line 1,289:


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang clojure>(require '[clojure.string :as string])
<syntaxhighlight lang="clojure">(require '[clojure.string :as string])


(def seconds-in-minute 60)
(def seconds-in-minute 60)
Line 1,316: Line 1,316:
(seconds->duration 7259)
(seconds->duration 7259)
(seconds->duration 86400)
(seconds->duration 86400)
(seconds->duration 6000000)</lang>
(seconds->duration 6000000)</syntaxhighlight>


{{out}}
{{out}}
Line 1,326: Line 1,326:


=={{header|CLU}}==
=={{header|CLU}}==
<lang clu>duration = proc (s: int) returns (string)
<syntaxhighlight lang="clu">duration = proc (s: int) returns (string)
own units: array[string] := array[string]$["wk","d","hr","min","sec"]
own units: array[string] := array[string]$["wk","d","hr","min","sec"]
own sizes: array[int] := array[int]$[2:7,24,60,60]
own sizes: array[int] := array[int]$[2:7,24,60,60]
Line 1,353: Line 1,353:
stream$putl(po, int$unparse(test) || " => " || duration(test))
stream$putl(po, int$unparse(test) || " => " || duration(test))
end
end
end start_up</lang>
end start_up</syntaxhighlight>
{{out}}
{{out}}
<pre>7259 => 2 hr, 59 sec
<pre>7259 => 2 hr, 59 sec
Line 1,360: Line 1,360:


=={{header|COBOL}}==
=={{header|COBOL}}==
<lang COBOL> identification division.
<syntaxhighlight lang="cobol"> identification division.
program-id. fmt-dura.
program-id. fmt-dura.
data division.
data division.
Line 1,433: Line 1,433:
.
.
end program fmt.
end program fmt.
end program fmt-dura.</lang>
end program fmt-dura.</syntaxhighlight>
<pre>Enter duration (seconds): 7259
<pre>Enter duration (seconds): 7259
2 hr, 59 sec
2 hr, 59 sec
Line 1,442: Line 1,442:


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>(defconstant +seconds-in-minute* 60)
<syntaxhighlight lang="lisp">(defconstant +seconds-in-minute* 60)
(defconstant +seconds-in-hour* (* 60 +seconds-in-minute*))
(defconstant +seconds-in-hour* (* 60 +seconds-in-minute*))
(defconstant +seconds-in-day* (* 24 +seconds-in-hour*))
(defconstant +seconds-in-day* (* 24 +seconds-in-hour*))
Line 1,463: Line 1,463:
(seconds->duration 86400)
(seconds->duration 86400)
(seconds->duration 6000000)
(seconds->duration 6000000)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,472: Line 1,472:


=={{header|D}}==
=={{header|D}}==
<syntaxhighlight lang="d">
<lang d>
import std.stdio, std.conv, std.algorithm;
import std.stdio, std.conv, std.algorithm;


Line 1,512: Line 1,512:
6_000_000.ConvertSeconds.writeln;
6_000_000.ConvertSeconds.writeln;
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,521: Line 1,521:


=={{header|EasyLang}}==
=={{header|EasyLang}}==
<lang>func split sec . s$ .
<syntaxhighlight lang="text">func split sec . s$ .
divs[] = [ 60 60 24 7 ]
divs[] = [ 60 60 24 7 ]
n$[] = [ "sec" "min" "hr" "d" "wk" ]
n$[] = [ "sec" "min" "hr" "d" "wk" ]
Line 1,545: Line 1,545:
print s$
print s$
call split 6000000 s$
call split 6000000 s$
print s$</lang>
print s$</syntaxhighlight>


{{out}}
{{out}}
Line 1,555: Line 1,555:


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>defmodule Convert do
<syntaxhighlight lang="elixir">defmodule Convert do
@minute 60
@minute 60
@hour @minute*60
@hour @minute*60
Line 1,575: Line 1,575:
Enum.each([7259, 86400, 6000000], fn sec ->
Enum.each([7259, 86400, 6000000], fn sec ->
:io.fwrite "~10w sec : ~s~n", [sec, Convert.sec_to_str(sec)]
:io.fwrite "~10w sec : ~s~n", [sec, Convert.sec_to_str(sec)]
end)</lang>
end)</syntaxhighlight>


{{out}}
{{out}}
Line 1,591: 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].
Function ''intercalate/2'' is copied from [https://github.com/tim/erlang-oauth/blob/master/src/oauth.erl a Tim Fletcher's GitHub repository].


<lang erlang>
<syntaxhighlight lang="erlang">
-module(convert_seconds).
-module(convert_seconds).


Line 1,681: Line 1,681:


% **************************************************
% **************************************************
</syntaxhighlight>
</lang>


Output:
Output:
Line 1,691: Line 1,691:


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>open System
<syntaxhighlight lang="fsharp">open System


let convert seconds =
let convert seconds =
Line 1,711: Line 1,711:
|> Seq.map (fun str -> let sec = UInt32.Parse str in (sec, convert sec))
|> Seq.map (fun str -> let sec = UInt32.Parse str in (sec, convert sec))
|> Seq.iter (fun (s, v) -> printfn "%10i = %s" s v)
|> Seq.iter (fun (s, v) -> printfn "%10i = %s" s v)
0</lang>
0</syntaxhighlight>
{{out}}
{{out}}
<pre>>RosettaCode 7259 86400 6000000
<pre>>RosettaCode 7259 86400 6000000
Line 1,719: Line 1,719:


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USING: assocs io kernel math math.parser qw sequences
<syntaxhighlight lang="factor">USING: assocs io kernel math math.parser qw sequences
sequences.generalizations ;
sequences.generalizations ;


Line 1,731: Line 1,731:
[ first "0" = ] reject [ " " join ] map ", " join print ;
[ first "0" = ] reject [ " " join ] map ", " join print ;
7259 86400 6000000 [ .time ] tri@</lang>
7259 86400 6000000 [ .time ] tri@</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,741: Line 1,741:
=={{header|Forth}}==
=={{header|Forth}}==
{{works with|Gforth|0.7.3}}
{{works with|Gforth|0.7.3}}
<lang Forth>CREATE C 0 ,
<syntaxhighlight lang="forth">CREATE C 0 ,
: ., C @ IF ." , " THEN 1 C ! ;
: ., C @ IF ." , " THEN 1 C ! ;
: .TIME ( n --)
: .TIME ( n --)
Line 1,748: Line 1,748:
[ 60 60 * ]L /MOD ?DUP-IF ., . ." hr" THEN
[ 60 60 * ]L /MOD ?DUP-IF ., . ." hr" THEN
[ 60 ]L /MOD ?DUP-IF ., . ." min" THEN
[ 60 ]L /MOD ?DUP-IF ., . ." min" THEN
?DUP-IF ., . ." sec" THEN 0 C ! ;</lang>
?DUP-IF ., . ." sec" THEN 0 C ! ;</syntaxhighlight>
{{out}}
{{out}}
<pre>2 hr, 59 sec
<pre>2 hr, 59 sec
Line 1,758: 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.
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.
SUBROUTINE PROUST(T) !Remembrance of time passed.
INTEGER T !The time, in seconds. Positive only, please.
INTEGER T !The time, in seconds. Positive only, please.
Line 1,796: Line 1,796:
CALL PROUST(-666)
CALL PROUST(-666)
END
END
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 1,808: Line 1,808:


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>'FreeBASIC version 1.05 32/64 bit
<syntaxhighlight lang="freebasic">'FreeBASIC version 1.05 32/64 bit


Sub Show(m As Long)
Sub Show(m As Long)
Line 1,844: Line 1,844:
Show 86400 seconds
Show 86400 seconds
Show 6000000 seconds
Show 6000000 seconds
sleep</lang>
sleep</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 1,855: 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.
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.


<lang frink>
<syntaxhighlight lang="frink">
wk := week
wk := week
n = eval[input["Enter duration in seconds: "]]
n = eval[input["Enter duration in seconds: "]]
Line 1,861: Line 1,861:
res =~ %s/, 0[^,]+//g
res =~ %s/, 0[^,]+//g
println[res]
println[res]
</syntaxhighlight>
</lang>


=={{header|Gambas}}==
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=d7f00b8a96a6f792f0164f622f0686df Click this link to run this code]'''
'''[https://gambas-playground.proko.eu/?gist=d7f00b8a96a6f792f0164f622f0686df Click this link to run this code]'''
<lang gambas>Public Sub Main()
<syntaxhighlight lang="gambas">Public Sub Main()
Dim iInput As Integer[] = [7259, 86400, 6000000] 'Input details
Dim iInput As Integer[] = [7259, 86400, 6000000] 'Input details
Dim iChecks As Integer[] = [604800, 86400, 3600, 60] 'Weeks, days, hours, mins in seconds
Dim iChecks As Integer[] = [604800, 86400, 3600, 60] 'Weeks, days, hours, mins in seconds
Line 1,895: Line 1,895:
Next
Next


End</lang>
End</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 1,904: Line 1,904:


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 1,953: Line 1,953:
return
return
}
}
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 1,962: Line 1,962:


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>import Control.Monad (forM_)
<syntaxhighlight lang="haskell">import Control.Monad (forM_)
import Data.List (intercalate, mapAccumR)
import Data.List (intercalate, mapAccumR)
import System.Environment (getArgs)
import System.Environment (getArgs)
Line 1,989: Line 1,989:
forM_ args $ \arg -> case readMaybe arg of
forM_ args $ \arg -> case readMaybe arg of
Just n -> printf "%7d seconds = %s\n" n (compoundDuration n)
Just n -> printf "%7d seconds = %s\n" n (compoundDuration n)
Nothing -> putStrLn $ "Invalid number of seconds: " ++ arg</lang>
Nothing -> putStrLn $ "Invalid number of seconds: " ++ arg</syntaxhighlight>


{{out}}
{{out}}
Line 2,001: 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:
Or, parameterising both the local names for these durations, and also the working assumptions about hours per day, and days per week:


<lang haskell>import Data.List (intercalate, mapAccumR)
<syntaxhighlight lang="haskell">import Data.List (intercalate, mapAccumR)


---------------- COMPOUND DURATION STRINGS ---------------
---------------- COMPOUND DURATION STRINGS ---------------
Line 2,071: Line 2,071:


putStrLn "\nor, at 8 hours per day, 5 days per week:"
putStrLn "\nor, at 8 hours per day, 5 days per week:"
mapM_ (putStrLn . translation names 5 8) tests</lang>
mapM_ (putStrLn . translation names 5 8) tests</syntaxhighlight>
{{Out}}
{{Out}}
<pre>Assuming 24/7:
<pre>Assuming 24/7:
Line 2,087: Line 2,087:
Implementation:
Implementation:


<lang J>fmtsecs=: verb define
<syntaxhighlight lang="j">fmtsecs=: verb define
seq=. 0 7 24 60 60 #: y
seq=. 0 7 24 60 60 #: y
}: ;:inv ,(0 ~: seq) # (8!:0 seq) ,. <;.2'wk,d,hr,min,sec,'
}: ;:inv ,(0 ~: seq) # (8!:0 seq) ,. <;.2'wk,d,hr,min,sec,'
)</lang>
)</syntaxhighlight>


The first line uses integer division with remainder to break the value in seconds into its components (weeks, days, hours, minutes, seconds).
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: Line 2,098:
Task examples:
Task examples:


<lang J> fmtsecs 7259
<syntaxhighlight lang="j"> fmtsecs 7259
2 hr, 59 sec
2 hr, 59 sec
fmtsecs 86400
fmtsecs 86400
1 d
1 d
fmtsecs 6000000
fmtsecs 6000000
9 wk, 6 d, 10 hr, 40 min</lang>
9 wk, 6 d, 10 hr, 40 min</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
<lang java>public class CompoundDuration {
<syntaxhighlight lang="java">public class CompoundDuration {


public static void main(String[] args) {
public static void main(String[] args) {
Line 2,136: Line 2,136:
return sec;
return sec;
}
}
}</lang>
}</syntaxhighlight>


<pre>2 hr, 59 sec
<pre>2 hr, 59 sec
Line 2,148: Line 2,148:
====ES5====
====ES5====


<lang JavaScript>(function () {
<syntaxhighlight lang="javascript">(function () {
'use strict';
'use strict';


Line 2,207: Line 2,207:


})();
})();
</syntaxhighlight>
</lang>


{{Out}}
{{Out}}
Line 2,216: Line 2,216:


====ES6====
====ES6====
<lang JavaScript>(() => {
<syntaxhighlight lang="javascript">(() => {
"use strict";
"use strict";


Line 2,263: Line 2,263:
// MAIN ---
// MAIN ---
return main();
return main();
})();</lang>
})();</syntaxhighlight>
{{Out}}
{{Out}}
<pre>7259 -> 2 hr, 59 sec
<pre>7259 -> 2 hr, 59 sec
Line 2,271: Line 2,271:
=={{header|jq}}==
=={{header|jq}}==
{{works with|jq|1.4}}
{{works with|jq|1.4}}
<lang jq>def seconds_to_time_string:
<syntaxhighlight lang="jq">def seconds_to_time_string:
def nonzero(text): floor | if . > 0 then "\(.) \(text)" else empty end;
def nonzero(text): floor | if . > 0 then "\(.) \(text)" else empty end;
if . == 0 then "0 sec"
if . == 0 then "0 sec"
Line 2,281: Line 2,281:
(. % 60 | nonzero("sec"))]
(. % 60 | nonzero("sec"))]
| join(", ")
| join(", ")
end;</lang>
end;</syntaxhighlight>


''Examples''':
''Examples''':
<lang jq>0, 7259, 86400, 6000000 | "\(.): \(seconds_to_time_string)"</lang>
<syntaxhighlight lang="jq">0, 7259, 86400, 6000000 | "\(.): \(seconds_to_time_string)"</syntaxhighlight>
{{out}}
{{out}}
<lang sh>$ jq -r -n -f Convert_seconds_to_compound_duration.jq
<syntaxhighlight lang="sh">$ jq -r -n -f Convert_seconds_to_compound_duration.jq
0: 0 sec
0: 0 sec
7259: 2 hr, 59 sec
7259: 2 hr, 59 sec
86400: 1 d
86400: 1 d
6000000: 9 wk, 6 d, 10 hr, 40 min</lang>
6000000: 9 wk, 6 d, 10 hr, 40 min</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==
<lang julia># 1.x
<syntaxhighlight lang="julia"># 1.x
function duration(sec::Integer)::String
function duration(sec::Integer)::String
t = Array{Int}([])
t = Array{Int}([])
Line 2,307: Line 2,307:
@show duration(86400)
@show duration(86400)
@show duration(6000000)
@show duration(6000000)
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,317: Line 2,317:


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>fun compoundDuration(n: Int): String {
<syntaxhighlight 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 "" // task doesn't ask for negative integers to be converted
if (n == 0) return "0 sec"
if (n == 0) return "0 sec"
Line 2,355: Line 2,355:
val durations = intArrayOf(0, 7, 84, 7259, 86400, 6000000)
val durations = intArrayOf(0, 7, 84, 7259, 86400, 6000000)
durations.forEach { println("$it\t-> ${compoundDuration(it)}") }
durations.forEach { println("$it\t-> ${compoundDuration(it)}") }
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,369: Line 2,369:
=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
I got a bit carried away and added 'years'...
I got a bit carried away and added 'years'...
<syntaxhighlight lang="lb">
<lang lb>
[start]
[start]
input "Enter SECONDS: "; seconds
input "Enter SECONDS: "; seconds
Line 2,458: Line 2,458:
print
print
goto [start]
goto [start]
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,474: Line 2,474:


=={{header|Lua}}==
=={{header|Lua}}==
<lang Lua>function duration (secs)
<syntaxhighlight lang="lua">function duration (secs)
local units, dur = {"wk", "d", "hr", "min"}, ""
local units, dur = {"wk", "d", "hr", "min"}, ""
for i, v in ipairs({604800, 86400, 3600, 60}) do
for i, v in ipairs({604800, 86400, 3600, 60}) do
Line 2,491: Line 2,491:
print(duration(7259))
print(duration(7259))
print(duration(86400))
print(duration(86400))
print(duration(6000000))</lang>
print(duration(6000000))</syntaxhighlight>


=={{header|Maple}}==
=={{header|Maple}}==
<syntaxhighlight lang="maple">
<lang Maple>
tim := proc (s) local weeks, days, hours, minutes, seconds;
tim := proc (s) local weeks, days, hours, minutes, seconds;
weeks := trunc((1/604800)*s);
weeks := trunc((1/604800)*s);
Line 2,503: 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)))
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;
end proc;
</syntaxhighlight>
</lang>


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>compoundDuration[x_Integer] :=
<syntaxhighlight lang="mathematica">compoundDuration[x_Integer] :=
StringJoin @@ (Riffle[
StringJoin @@ (Riffle[
ToString /@ ((({Floor[x/604800],
ToString /@ ((({Floor[x/604800],
Line 2,517: Line 2,517:
Grid[Table[{n, "secs =",
Grid[Table[{n, "secs =",
compoundDuration[n]}, {n, {7259, 86400, 6000000}}],
compoundDuration[n]}, {n, {7259, 86400, 6000000}}],
Alignment -> {Left, Baseline}]</lang>
Alignment -> {Left, Baseline}]</syntaxhighlight>


{{out}}
{{out}}
Line 2,525: Line 2,525:


=={{header|Nim}}==
=={{header|Nim}}==
<lang Nim>from strutils import addSep
<syntaxhighlight lang="nim">from strutils import addSep


const
const
Line 2,552: Line 2,552:
when isMainModule:
when isMainModule:
for sec in [7259, 86400, 6000000]:
for sec in [7259, 86400, 6000000]:
echo sec, "s = ", $$sec</lang>
echo sec, "s = ", $$sec</syntaxhighlight>


{{out}}
{{out}}
Line 2,563: 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).
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
<syntaxhighlight lang="nim">import times
from algorithm import reversed
from algorithm import reversed
from strutils import addSep
from strutils import addSep
Line 2,589: Line 2,589:
when isMainModule:
when isMainModule:
for sec in [7259, 86400, 6000000]:
for sec in [7259, 86400, 6000000]:
echo sec, "s = ", $$sec</lang>
echo sec, "s = ", $$sec</syntaxhighlight>


{{out}}
{{out}}
Line 2,597: Line 2,597:
=={{header|OCaml}}==
=={{header|OCaml}}==
{{works with|OCaml|4.03+}}
{{works with|OCaml|4.03+}}
<lang ocaml>let divisors = [
<syntaxhighlight lang="ocaml">let divisors = [
(max_int, "wk"); (* many wk = many wk *)
(max_int, "wk"); (* many wk = many wk *)
(7, "d"); (* 7 d = 1 wk *)
(7, "d"); (* 7 d = 1 wk *)
Line 2,668: Line 2,668:
n calc s
n calc s
in
in
List.iter testit test_cases</lang>
List.iter testit test_cases</syntaxhighlight>
{{out}}
{{out}}
[PASS] 7259 seconds -> 2 hr, 59 sec; expected: 2 hr, 59 sec
[PASS] 7259 seconds -> 2 hr, 59 sec; expected: 2 hr, 59 sec
Line 2,683: Line 2,683:
{{Works with|PARI/GP|2.7.4 and above}}
{{Works with|PARI/GP|2.7.4 and above}}


<lang parigp>
<syntaxhighlight lang="parigp">
\\ Convert seconds to compound duration
\\ Convert seconds to compound duration
\\ 4/11/16 aev
\\ 4/11/16 aev
Line 2,700: Line 2,700:
print(secs2compdur(6000000));
print(secs2compdur(6000000));
}
}
</lang>
</syntaxhighlight>


{{Output}}
{{Output}}
Line 2,712: Line 2,712:
=={{header|Pascal}}==
=={{header|Pascal}}==
{{works with|Extended Pascal}}
{{works with|Extended Pascal}}
<lang pascal>program convertSecondsToCompoundDuration(output);
<syntaxhighlight lang="pascal">program convertSecondsToCompoundDuration(output);


const
const
Line 2,826: Line 2,826:
writeLn( 86400, ' seconds are “', timeSpanString(86400), '”');
writeLn( 86400, ' seconds are “', timeSpanString(86400), '”');
writeLn(6000000, ' seconds are “', timeSpanString(6000000), '”')
writeLn(6000000, ' seconds are “', timeSpanString(6000000), '”')
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
7259 seconds are “2 hr, 59 sec”
7259 seconds are “2 hr, 59 sec”
Line 2,835: Line 2,835:


===Direct calculation===
===Direct calculation===
<lang perl>use strict;
<syntaxhighlight lang="perl">use strict;
use warnings;
use warnings;


Line 2,852: Line 2,852:
for (7259, 86400, 6000000) {
for (7259, 86400, 6000000) {
printf "%7d sec = %s\n", $_, compound_duration($_)
printf "%7d sec = %s\n", $_, compound_duration($_)
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre> 7259 sec = 2 hr, 59 sec
<pre> 7259 sec = 2 hr, 59 sec
Line 2,860: Line 2,860:
===Using polymod===
===Using polymod===
More general approach for mixed-radix conversions.
More general approach for mixed-radix conversions.
<lang perl>use strict;
<syntaxhighlight lang="perl">use strict;
use warnings;
use warnings;
use Math::AnyNum 'polymod';
use Math::AnyNum 'polymod';
Line 2,878: Line 2,878:
for (<7259 86400 6000000 3380521>) {
for (<7259 86400 6000000 3380521>) {
printf "%7d sec = %s\n", $_, compound_duration($_)
printf "%7d sec = %s\n", $_, compound_duration($_)
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre> 7259 sec = 2 hr, 59 sec
<pre> 7259 sec = 2 hr, 59 sec
Line 2,887: Line 2,887:
=={{header|Phix}}==
=={{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)
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)
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<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;">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;">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>
<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>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 2,900: Line 2,900:
</pre>
</pre>
You may also be interested in the timedelta() function, which converts durations to seconds, eg:
You may also be interested in the timedelta() function, which converts durations to seconds, eg:
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<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: #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>
<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>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 2,911: Line 2,911:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(for Sec (7259 86400 6000000)
<syntaxhighlight lang="picolisp">(for Sec (7259 86400 6000000)
(tab (-10 -30)
(tab (-10 -30)
Sec
Sec
Line 2,921: Line 2,921:
(pack @ " " Str) ) )
(pack @ " " Str) ) )
(604800 86400 3600 60 1)
(604800 86400 3600 60 1)
'("wk" "d" "hr" "min" "sec") ) ) ) )</lang>
'("wk" "d" "hr" "min" "sec") ) ) ) )</syntaxhighlight>
Output:
Output:
<pre>7259 2 hr, 59 sec
<pre>7259 2 hr, 59 sec
Line 2,928: Line 2,928:


=={{header|PL/I}}==
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
/* Convert seconds to Compound Duration (weeks, days, hours, minutes, seconds). */
/* Convert seconds to Compound Duration (weeks, days, hours, minutes, seconds). */


Line 2,956: Line 2,956:
end;
end;
end cvt;
end cvt;
</syntaxhighlight>
</lang>
Results:
Results:
<pre>
<pre>
Line 2,972: Line 2,972:


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Get-Time
function Get-Time
{
{
Line 3,089: Line 3,089:
}
}
}
}
</syntaxhighlight>
</lang>


{{Out}}
{{Out}}
Line 3,127: Line 3,127:
See below for examples.
See below for examples.


<lang prolog>:- use_module(library(clpfd)).
<syntaxhighlight lang="prolog">:- use_module(library(clpfd)).


% helper to perform the operation with just a number.
% helper to perform the operation with just a number.
Line 3,170: Line 3,170:
time_type(hr, 60 * 60).
time_type(hr, 60 * 60).
time_type(min, 60).
time_type(min, 60).
time_type(sec, 1).</lang>
time_type(sec, 1).</syntaxhighlight>


{{out}}
{{out}}
Line 3,185: Line 3,185:


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">
<lang PureBasic>
EnableExplicit
EnableExplicit


Line 3,241: Line 3,241:
CloseConsole()
CloseConsole()
EndIf
EndIf
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 3,253: Line 3,253:


===Python: Procedural===
===Python: Procedural===
<lang python>>>> def duration(seconds):
<syntaxhighlight lang="python">>>> def duration(seconds):
t= []
t= []
for dm in (60, 60, 24, 7):
for dm in (60, 60, 24, 7):
Line 3,270: Line 3,270:
86400 sec = 1 d
86400 sec = 1 d
6000000 sec = 9 wk, 6 d, 10 hr, 40 min
6000000 sec = 9 wk, 6 d, 10 hr, 40 min
>>> </lang>
>>> </syntaxhighlight>


===Python: Functional===
===Python: Functional===
<lang python>>>> def duration(seconds, _maxweeks=99999999999):
<syntaxhighlight lang="python">>>> def duration(seconds, _maxweeks=99999999999):
return ', '.join('%d %s' % (num, unit)
return ', '.join('%d %s' % (num, unit)
for num, unit in zip([(seconds // d) % m
for num, unit in zip([(seconds // d) % m
Line 3,289: Line 3,289:
86400 sec = 1 d
86400 sec = 1 d
6000000 sec = 9 wk, 6 d, 10 hr, 40 min
6000000 sec = 9 wk, 6 d, 10 hr, 40 min
>>> </lang>
>>> </syntaxhighlight>


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):
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):


<lang python>'''Compound duration'''
<syntaxhighlight lang="python">'''Compound duration'''


from functools import reduce
from functools import reduce
Line 3,379: Line 3,379:
# MAIN ---
# MAIN ---
if __name__ == '__main__':
if __name__ == '__main__':
main()</lang>
main()</syntaxhighlight>
{{Out}}
{{Out}}
<pre>Compound durations from numbers of seconds:
<pre>Compound durations from numbers of seconds:
Line 3,389: Line 3,389:
=={{header|Quackery}}==
=={{header|Quackery}}==


<lang Quackery> [ ' [ 60 60 24 7 ]
<syntaxhighlight lang="quackery"> [ ' [ 60 60 24 7 ]
witheach [ /mod swap ]
witheach [ /mod swap ]
$ ""
$ ""
Line 3,407: Line 3,407:
say " seconds is "
say " seconds is "
duration$ echo$
duration$ echo$
say "." cr ]</lang>
say "." cr ]</syntaxhighlight>


{{Out}}
{{Out}}
Line 3,419: Line 3,419:
=={{header|Racket}}==
=={{header|Racket}}==


<lang racket>#lang racket/base
<syntaxhighlight lang="racket">#lang racket/base
(require racket/string
(require racket/string
racket/list)
racket/list)
Line 3,450: Line 3,450:
(check-equal? (seconds->compound-duration-string 6000000) "9 wk, 6 d, 10 hr, 40 min"))
(check-equal? (seconds->compound-duration-string 6000000) "9 wk, 6 d, 10 hr, 40 min"))


;; Tim Brown 2015-07-21</lang>
;; Tim Brown 2015-07-21</syntaxhighlight>


{{out}}
{{out}}
Line 3,460: 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:
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:


<lang perl6>sub compound-duration ($seconds) {
<syntaxhighlight lang="raku" line>sub compound-duration ($seconds) {
($seconds.polymod(60, 60, 24, 7) Z <sec min hr d wk>)
($seconds.polymod(60, 60, 24, 7) Z <sec min hr d wk>)
.grep(*[0]).reverse.join(", ")
.grep(*[0]).reverse.join(", ")
Line 3,469: Line 3,469:
for 7259, 86400, 6000000 {
for 7259, 86400, 6000000 {
say "{.fmt: '%7d'} sec = {compound-duration $_}";
say "{.fmt: '%7d'} sec = {compound-duration $_}";
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 3,480: Line 3,480:
=={{header|REXX}}==
=={{header|REXX}}==
===version 1===
===version 1===
<lang rexx>/* REXX ---------------------------------------------------------------
<syntaxhighlight lang="rexx">/* REXX ---------------------------------------------------------------
* Format seconds into a time string
* Format seconds into a time string
*--------------------------------------------------------------------*/
*--------------------------------------------------------------------*/
Line 3,525: Line 3,525:
a=what%how
a=what%how
b=what//how
b=what//how
Return a b</lang>
Return a b</syntaxhighlight>
{{out}}
{{out}}
<pre>2 hr, 59 sec
<pre>2 hr, 59 sec
Line 3,536: Line 3,536:
===version 2===
===version 2===
This REXX version can also handle fractional (seconds) as well as values of zero (time units).
This REXX version can also handle fractional (seconds) as well as values of zero (time units).
<lang rexx>/*rexx program demonstrates how to convert a number of seconds to bigger time units.*/
<syntaxhighlight 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.*/
parse arg @; if @='' then @=7259 86400 6000000 /*Not specified? Then use the default.*/


Line 3,554: Line 3,554:
return $
return $
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
timeU: parse arg u,$; _= x%u; if _==0 then return ''; x= x - _*u; return _ $","</lang>
timeU: parse arg u,$; _= x%u; if _==0 then return ''; x= x - _*u; return _ $","</syntaxhighlight>
{{out|output|text=&nbsp; when using the default (internal) inputs:}}
{{out|output|text=&nbsp; when using the default (internal) inputs:}}
<pre>
<pre>
Line 3,570: Line 3,570:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
sec = 6000005
sec = 6000005
week = floor(sec/60/60/24/7)
week = floor(sec/60/60/24/7)
Line 3,587: Line 3,587:
if second > 0 see second
if second > 0 see second
see " seconds" + nl ok
see " seconds" + nl ok
</syntaxhighlight>
</lang>


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>MINUTE = 60
<syntaxhighlight lang="ruby">MINUTE = 60
HOUR = MINUTE*60
HOUR = MINUTE*60
DAY = HOUR*24
DAY = HOUR*24
Line 3,604: Line 3,604:
end
end


[7259, 86400, 6000000].each{|t| puts "#{t}\t: #{sec_to_str(t)}"}</lang>
[7259, 86400, 6000000].each{|t| puts "#{t}\t: #{sec_to_str(t)}"}</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 3,613: Line 3,613:


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>sec = 6000005
<syntaxhighlight lang="runbasic">sec = 6000005
week = int(sec/60/60/24/7)
week = int(sec/60/60/24/7)
day = int(sec/60/60/24) mod 7
day = int(sec/60/60/24) mod 7
Line 3,625: Line 3,625:
if hour > 0 then print hour;" hours ";
if hour > 0 then print hour;" hours ";
if minute > 0 then print minute;" minutes ";
if minute > 0 then print minute;" minutes ";
if second > 0 then print second;" seconds"</lang>
if second > 0 then print second;" seconds"</syntaxhighlight>


=={{header|Rust}}==
=={{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.
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.
<lang rust>use std::fmt;
<syntaxhighlight lang="rust">use std::fmt;




Line 3,674: Line 3,674:
ct.balance();
ct.balance();
println!("After: {}", ct);
println!("After: {}", ct);
}</lang>
}</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>//Converting Seconds to Compound Duration
<syntaxhighlight lang="scala">//Converting Seconds to Compound Duration


object seconds{
object seconds{
Line 3,705: Line 3,705:
println("Second = " + sec)
println("Second = " + sec)
}
}
}</lang>
}</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==
Line 3,713: Line 3,713:
This version uses delete from SRFI 1 and string-join from SRFI 13:
This version uses delete from SRFI 1 and string-join from SRFI 13:


<lang scheme>
<syntaxhighlight lang="scheme">
(import (scheme base)
(import (scheme base)
(scheme write)
(scheme write)
Line 3,742: Line 3,742:
(display (seconds->duration 86400)) (newline)
(display (seconds->duration 86400)) (newline)
(display (seconds->duration 6000000)) (newline)
(display (seconds->duration 6000000)) (newline)
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 3,753: Line 3,753:
=={{header|Sidef}}==
=={{header|Sidef}}==
{{trans|Raku}}
{{trans|Raku}}
<lang ruby>func polymod(n, *divs) {
<syntaxhighlight lang="ruby">func polymod(n, *divs) {
gather {
gather {
divs.each { |i|
divs.each { |i|
Line 3,771: Line 3,771:
[7259, 86400, 6000000].each { |s|
[7259, 86400, 6000000].each { |s|
say "#{'%7d' % s} sec = #{compound_duration(s)}"
say "#{'%7d' % s} sec = #{compound_duration(s)}"
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 3,781: Line 3,781:


=={{header|Standard ML}}==
=={{header|Standard ML}}==
<lang sml>local
<syntaxhighlight lang="sml">local
fun fmtNonZero (0, _, list) = list
fun fmtNonZero (0, _, list) = list
| fmtNonZero (n, s, list) = Int.toString n ^ " " ^ s :: list
| fmtNonZero (n, s, list) = Int.toString n ^ " " ^ s :: list
Line 3,796: Line 3,796:
end
end


val () = app (fn s => print (compoundDuration s ^ "\n")) [7259, 86400, 6000000]</lang>
val () = app (fn s => print (compoundDuration s ^ "\n")) [7259, 86400, 6000000]</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
<lang swift>func duration (_ secs:Int) -> String {
<syntaxhighlight lang="swift">func duration (_ secs:Int) -> String {
if secs <= 0 { return "" }
if secs <= 0 { return "" }
let units = [(604800,"wk"), (86400,"d"), (3600,"hr"), (60,"min")]
let units = [(604800,"wk"), (86400,"d"), (3600,"hr"), (60,"min")]
Line 3,820: Line 3,820:
print(duration(7259))
print(duration(7259))
print(duration(86400))
print(duration(86400))
print(duration(6000000))</lang>
print(duration(6000000))</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==
Line 3,826: Line 3,826:
The data-driven procedure below can be customised to use different breakpoints, simply by editing the dictionary.
The data-driven procedure below can be customised to use different breakpoints, simply by editing the dictionary.


<lang Tcl>proc sec2str {i} {
<syntaxhighlight lang="tcl">proc sec2str {i} {
set factors {
set factors {
sec 60
sec 60
Line 3,863: Line 3,863:
check {sec2str 7259} {2 hr, 59 sec}
check {sec2str 7259} {2 hr, 59 sec}
check {sec2str 86400} {1 d}
check {sec2str 86400} {1 d}
check {sec2str 6000000} {9 wk, 6 d, 10 hr, 40 min}</lang>
check {sec2str 6000000} {9 wk, 6 d, 10 hr, 40 min}</syntaxhighlight>


{{Out}}
{{Out}}
Line 3,872: Line 3,872:
=={{header|uBasic/4tH}}==
=={{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.
Since uBasic/4tH is integer-only, it is hard to return a string. However, it is capable to transform an integer value as required.
<lang>Proc _CompoundDuration(7259)
<syntaxhighlight lang="text">Proc _CompoundDuration(7259)
Proc _CompoundDuration(86400)
Proc _CompoundDuration(86400)
Proc _CompoundDuration(6000000)
Proc _CompoundDuration(6000000)
Line 3,910: Line 3,910:
_d Print " d"; : Return
_d Print " d"; : Return
_hr Print " hr"; : Return
_hr Print " hr"; : Return
_min Print " min"; : Return</lang>
_min Print " min"; : Return</syntaxhighlight>
{{out}}
{{out}}
<pre>2 hr, 59 sec
<pre>2 hr, 59 sec
Line 3,919: Line 3,919:


=={{header|VBA}}==
=={{header|VBA}}==
<lang vb>Private Function compound_duration(ByVal seconds As Long) As String
<syntaxhighlight lang="vb">Private Function compound_duration(ByVal seconds As Long) As String
minutes = 60
minutes = 60
hours = 60 * minutes
hours = 60 * minutes
Line 3,949: Line 3,949:
Debug.Print compound_duration(86400)
Debug.Print compound_duration(86400)
Debug.Print compound_duration(6000000)
Debug.Print compound_duration(6000000)
End Sub</lang>{{out}}
End Sub</syntaxhighlight>{{out}}
<pre>2 hr, 59 sec
<pre>2 hr, 59 sec
1 d
1 d
Line 3,955: Line 3,955:


=={{header|VBScript}}==
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
Function compound_duration(n)
Function compound_duration(n)
Do Until n = 0
Do Until n = 0
Line 3,993: Line 3,993:
WScript.StdOut.WriteLine compound_duration(86400)
WScript.StdOut.WriteLine compound_duration(86400)
WScript.StdOut.WriteLine compound_duration(6000000)
WScript.StdOut.WriteLine compound_duration(6000000)
</syntaxhighlight>
</lang>


{{Out}}
{{Out}}
Line 4,003: Line 4,003:


=={{header|Wren}}==
=={{header|Wren}}==
<lang ecmascript>var duration = Fn.new { |s|
<syntaxhighlight lang="ecmascript">var duration = Fn.new { |s|
if (s < 1) return "0 sec"
if (s < 1) return "0 sec"
var dur = ""
var dur = ""
Line 4,021: Line 4,021:
}
}


for (s in [7259, 86400, 6000000]) System.print(duration.call(s))</lang>
for (s in [7259, 86400, 6000000]) System.print(duration.call(s))</syntaxhighlight>


{{out}}
{{out}}
Line 4,031: Line 4,031:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>char Str(80);
<syntaxhighlight lang="xpl0">char Str(80);
func Duration(Sec); \Convert seconds to compound duration
func Duration(Sec); \Convert seconds to compound duration
int Sec, Amt, Unit, DoComma, I, Quot;
int Sec, Amt, Unit, DoComma, I, Quot;
Line 4,058: Line 4,058:
Text(0, Duration(86400));
Text(0, Duration(86400));
Text(0, Duration(6_000_000));
Text(0, Duration(6_000_000));
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 4,068: Line 4,068:


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>fcn toWDHMS(sec){ //-->(wk,d,h,m,s)
<syntaxhighlight lang="zkl">fcn toWDHMS(sec){ //-->(wk,d,h,m,s)
r,b:=List(),0;
r,b:=List(),0;
foreach u in (T(60,60,24,7)){
foreach u in (T(60,60,24,7)){
Line 4,075: Line 4,075:
}
}
r.append(sec).reverse()
r.append(sec).reverse()
}</lang>
}</syntaxhighlight>
Or, if you like to be concise:
Or, if you like to be concise:
<lang zkl>fcn toWDHMS(sec){ //-->(wk,d,h,m,s)
<syntaxhighlight 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 },
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();
sec,r:=List()):r.append(_).reverse();
}</lang>
}</syntaxhighlight>
were the ":" op takes the left result and stuffs it into the "_" position.
were the ":" op takes the left result and stuffs it into the "_" position.
<lang zkl>units:=T(" wk"," d"," hr"," min"," sec");
<syntaxhighlight lang="zkl">units:=T(" wk"," d"," hr"," min"," sec");
foreach s in (T(7259,86400,6000000)){
foreach s in (T(7259,86400,6000000)){
toWDHMS(s).zip(units).pump(List,fcn([(t,u)]){ t and String(t,u) or "" })
toWDHMS(s).zip(units).pump(List,fcn([(t,u)]){ t and String(t,u) or "" })
.filter().concat(", ").println();
.filter().concat(", ").println();
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,096: Line 4,096:
=={{header|ZX Spectrum Basic}}==
=={{header|ZX Spectrum Basic}}==
{{trans|AWK}}
{{trans|AWK}}
<lang zxbasic>10 LET m=60: LET h=60*m: LET d=h*24: LET w=d*7
<syntaxhighlight 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
20 DATA 10,7259,86400,6000000,0,1,60,3600,604799,604800,694861
30 READ n
30 READ n
Line 4,117: Line 4,117:
200 NEXT i
200 NEXT i
210 STOP
210 STOP
220 DEF FN m(a,b)=a-INT (a/b)*b</lang>
220 DEF FN m(a,b)=a-INT (a/b)*b</syntaxhighlight>