1
0
dotfiles/.config/zsh/lib/time.zsh

42 lines
804 B
Bash
Raw Normal View History

2021-03-21 18:25:10 +03:00
#!/bin/zsh
z-ts-to-human() {
2024-01-16 02:55:39 +03:00
local t s n d h m f x
2022-07-19 02:41:45 +03:00
t=$1
2024-01-27 00:10:58 +03:00
t=$[ float(t) ]
s=$[ int(t) ]
n=$[ int((t - s) * (10**9)) ]
2021-03-21 18:25:10 +03:00
t=$s
2022-07-19 02:41:45 +03:00
d=0 h=0 m=0
2021-03-21 18:25:10 +03:00
if [ $t -ge 86400 ] ; then
2024-01-27 00:10:58 +03:00
d=$[ t / 86400 ]
t=$[ t % 86400 ]
2021-03-21 18:25:10 +03:00
fi
if [ $t -ge 3600 ] ; then
2024-01-27 00:10:58 +03:00
h=$[ t / 3600 ]
t=$[ t % 3600 ]
2021-03-21 18:25:10 +03:00
fi
if [ $t -ge 60 ] ; then
2024-01-27 00:10:58 +03:00
m=$[ t / 60 ]
t=$[ t % 60 ]
2021-03-21 18:25:10 +03:00
fi
2024-01-16 02:55:39 +03:00
## strftime does desired rounding for $n/(10**9) internally
f=$(strftime '%s.%6.' $t $n)
2021-03-21 18:25:10 +03:00
## keep math in sync with format above
2024-01-16 02:55:39 +03:00
x=3
2021-03-21 18:25:10 +03:00
case "$2" in
2024-01-27 00:10:58 +03:00
0 ) x=7 ;;
[1-6] ) x=$[ 6 - $2 ] ;;
2021-03-21 18:25:10 +03:00
esac
[ $x -gt 0 ] && f="${f:0:-$x}s"
[ $s -ge 60 ] && f="${m}m:$f"
[ $s -ge 3600 ] && f="${h}h:$f"
[ $s -ge 86400 ] && f="${d}d:$f"
2022-07-19 02:41:45 +03:00
2021-03-21 18:25:10 +03:00
echo "$f"
}