bash, get current time in milliseconds since midnight

user788171 picture user788171 · Apr 23, 2013 · Viewed 8.4k times · Source

Is there a way to get the current milliseconds past midnight in bash? And if there is a way to do it entirely in bash, how good or bad is the precision of that timestamp?

Answer

fedorqui 'SO stop harming' picture fedorqui 'SO stop harming' · Apr 23, 2013

You can get today's midnight with:

date -d 'today 00:00:00'

in UNIX stamp:

date -d 'today 00:00:00' "+%s"

So if you want to get the difference, do:

midnight=$(date -d 'today 00:00:00' "+%s")
now=$(date "+%s")
diff_mills=$(( ($now - $midnight) * 1000 ))

as %s indicates seconds, we have to *1000 to get milliseconds.


With %N (nanoseconds):

midnight=$(date -d 'today 00:00:00' "+%s.%N")
now=$(date "+%s.%N")
diff_mills=$(echo "( $now - $midnight ) * 1000" | bc)