0

Updated answer: simple solution with built-in date program on macOS.

Adapted from https://stackoverflow.com/a/66928998/7299097.

$ date -ju -f "%s" 12345 "+%T"
03:25:45

Note: a drawback is that it does not support 86400 seconds or more (one day).


Original Question below.

The following post mentioned this is possible in bash, but apparently Mac's Terminal is different. So how should one convert an integer representing seconds into something like Day HH:MM:SS? I don't think I've come across an answer for Mac Terminal's zsh and macOS's date, printf program yet.

Work for up to 23:59:59 in bash:

From https://stackoverflow.com/a/27442175/7299097

$ TZ=UTC0 printf '%(%H:%M:%S)T\n' 12345
03:25:45

Not so in zsh with Terminal on Mac:

%  TZ=UTC0 printf '%(%H:%M:%S)T\n' 12345 
printf: %(: invalid directive

Even if you temporarily switch to bash like this:

% bash

The default interactive shell is now zsh.
To update your account to use zsh, please run `chsh -s /bin/zsh`.
For more details, please visit https://support.apple.com/kb/HT208050.
bash-3.2$
bash-3.2$ TZ=UTC0 printf '%(%H:%M:%S)T\n' 12345
bash: printf: `(': invalid format character

Also, -d on macOS is setting daylight saving time, apparently:

(in man date)
    -d _dst_  Set the kernel's value for daylight saving time...

What is a viable solution? If I don't install any packages from Homebrew, and I don't

jackxujh
  • 983
  • 10
  • 31
  • Does this answer your question? [Convert seconds to hours, minutes, seconds](https://stackoverflow.com/q/12199631); the [2nd answer](https://stackoverflow.com/a/29269811/7366100) mentions installing/using `GNU date` on MacOS, otherwise several other answers that may be of use ... – markp-fuso Aug 30 '21 at 23:20
  • How about awk's `strftime`? – LMC Aug 30 '21 at 23:59
  • AIUI the `%(...)` format for `printf` was added in bash v4, but macOS only comes with v3.2.57. ccpizza's solution [here](https://stackoverflow.com/questions/12199631/convert-seconds-to-hours-minutes-seconds/66928998#66928998) (or the version in my comment) should work for in either shell for times up to 23:59:59; if the time might be more than that, you need one of the solutions that does the math. – Gordon Davisson Aug 31 '21 at 00:08
  • @LMC I don't think macOS's awk support strftime. – jackxujh Aug 31 '21 at 00:24
  • @jackxujh: Why don't you simply split your H:M:S string on the colon, so that you get the individual numbers, and then do the multiplication using shell arithmetic? – user1934428 Aug 31 '21 at 06:12

0 Answers0