Convert seconds to compound duration: Difference between revisions
Content added Content deleted
(→{{header|AppleScript}}: Moved later post to below the previous one and added text.) |
m (→{{header|AppleScript}}: Tabs -> 4spaces) |
||
Line 436: | Line 436: | ||
<lang applescript>on secondsToCompoundDuration(s) |
<lang applescript>on secondsToCompoundDuration(s) |
||
if ((s's class is not integer) or (s < 0)) then |
|||
error "secondsToCompoundDuration() handler only accepts positive integers." |
|||
else if (s = 0) then |
|||
-- The task description notwithstanding, return "0 sec" if the input is the positive integer 0. |
|||
set output to "0 sec" |
|||
else |
|||
-- Otherwise perform the described task. |
|||
set suffixes to {" wk", " d", " hr", " min", " sec"} |
|||
-- AppleScript has constants for the number of seconds in a week, a day, an hour, and a minute. |
|||
set durationConstants to {weeks, days, hours, minutes, 1} |
|||
-- Initialise a list to collect the output. |
|||
set output to {} |
|||
-- Work through the list of constants. |
|||
repeat with i from 1 to 5 |
|||
-- Get the next constant and divide the number of seconds by it to get the number of corresponding units. |
|||
set thisConstant to item i of durationConstants |
|||
set unitValue to s div thisConstant |
|||
-- If the number of units isn't zero, coerce it to text, concatenate the corresponding suffix, and add the result to the output list. |
|||
if (unitValue > 0) then set end of output to (unitValue as text) & item i of suffixes |
|||
-- Get the number of seconds left over for use in the next iteration of the repeat. |
|||
set s to s mod thisConstant |
|||
-- Short-cut out of the repeat if no seconds remaining, although this isn't strictly necessary. |
|||
if (s = 0) then exit repeat |
|||
end repeat |
|||
-- Coerce the list of collected results to a single text using ", " as a delimiter. |
|||
set astid to AppleScript's text item delimiters |
|||
set AppleScript's text item delimiters to ", " |
|||
set output to output as text |
|||
set AppleScript's text item delimiters to astid |
|||
end if |
|||
return output |
|||
end secondsToCompoundDuration |
end secondsToCompoundDuration |
||
return secondsToCompoundDuration(7259) & linefeed & ¬ |
return secondsToCompoundDuration(7259) & linefeed & ¬ |
||
secondsToCompoundDuration(86400) & linefeed & ¬ |
|||
secondsToCompoundDuration(6000000)</lang> |
|||
{{output}} |
{{output}} |