1

I would like to turn a number-of-seconds-since midnight into an HH:MM:SS formatted string.

For example, the number 17672 should turn into the string '04:54:32'. I can do the math to get the integer components, like so:

      T←17672
      H←⌊T÷3600
      MS←3600|T
      M←⌊MS÷60
      S←60|T
      H M S
4 54 32

But I do not know how to join the three components of this array into a string (separated by colons), and left pad each time component with a zero. For example, I would want

6 0 8

to be '06:00:08'.

I can use either GNU APL or the online ngn-apl

Ray Toal
  • 86,166
  • 18
  • 182
  • 232

2 Answers2

3

In extended APL (all modern APLs) you can use

1↓∊':',¨¯2↑¨⍕¨100+24 60 60⊤T

ngn/apl has a non-conforming so you'll need

1↓∊':',¨¯2↑¨,¨⍕¨100+24 60 60⊤T

Try it online!

You in Dyalog, GNU and ngn/apl you can make a dfn (lambda) out of it by enclosing it in braces. Try it in ngn/apl and in Dyalog APL.

Using Dyalog APL version 16.0 or higher, you can use the @ operator to place colons:

{1↓':'@4 7∊⍕¨100+24 60 60⊤⍵}

Try it online!

Adám
  • 6,573
  • 20
  • 37
2

The first step is to improve the calculation by using the "encode"-function:

      24 60 60⊤17672
4 54 32

To format these numbers and insert the colon, I typically use ⎕FMT which is a vendor-specific function to format numbers as strings. A general way to do this in most APLs might be this:

     a←,⍕3 1⍴24 60 60⊤17672
     1↓,':',3 2⍴('0',a)[1+(⍳⍴a)×a≠' ']
04:54:32

Finally, instead of executing this in the session, you could put it into a function:

R←FormatSecs secs;a
a←,⍕3 1⍴60 60 60⊤secs
R←1↓,':',3 2⍴('0',a)[1+(⍳⍴a)×a≠' ']

Let's test it:

 FormatSecs 17672
04:54:32

Task accomplished ;-)

MBaas
  • 7,248
  • 6
  • 44
  • 61
  • Great stuff here! I did indeed desire a function, which I produced here https://ngn.github.io/apl/web/#code=%0Atime%20%u2190%20%7B%0A%20%20H%20%u2190%20%u230A%20%u2375%20%F7%203600%20%0A%20%20MS%20%u2190%203600%20%7C%20%u2375%20%0A%20%20M%20%u2190%20%u230A%20MS%20%F7%2060%20%0A%20%20S%20%u2190%2060%20%7C%20%u2375%20%0A%20%20H%2C%27%3A%27%2CM%2C%27%3A%27%2CS%0A%7D%0A%0Atime%2011%201%20%u2374%20%u230A%28%28%u2373%2011%29%20+%200.5%29%20%D7%2043200.0%20%F7%2011%0A but unfortunately got spaces between my colons. `encode` is awesome. – Ray Toal May 23 '17 at 05:49
  • Actually, the reason you had these blanks in your results is that you left the numbers as numbers and produced a heterogenous result - then APL inserts blanks as separators. You could improve that code by doing `H ←¯2↑'0',⍕ ⌊ ⍵ ÷ 3600`etc. – MBaas May 23 '17 at 05:59
  • Alternatively, R ← 1 ↓ , ':' , 0 1↓⍕(0 60 60 ⊤ X)∘.+,100 – Lobachevsky Jun 02 '17 at 12:50