How do I find seconds since midnight?
To avoid race conditions, still assuming GNU date:
eval "$(date +'today=%F now=%s')"
midnight=$(date -d "$today 0" +%s)
echo "$((now - midnight))"
With zsh
, you can do it internally:
zmodload zsh/datetime
now=$EPOCHSECONDS
strftime -s today %F $now
strftime -rs midnight %F $today
echo $((now - midnight))
Portably, in timezones where there's no daylight saving switch, you could do:
IFS=:
set -- $(date +%T)
echo "$((${1#0} * 3600 + ${2#0} * 60 + ${3#0}))"
The ${X#0}
is to strip leading 0s which in some shells like bash
, dash
and posh
cause problems with 09
(where the shell complains about it being an invalid octal number).
There is no need for any arithmetic expression, just use pure date:
date -d "1970-01-01 UTC $(date +%T)" +%s
Based on bash, get current time in milliseconds since midnight, on a GNU system, it can be done like this:
$ now=$(date '+%s')
$ midnight=$(date -d 'today 00:00:00' '+%s')
$ echo $(( now - midnight ))
53983