Search code examples
bashtimemilliseconds

bash, get current time in milliseconds since midnight


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?


Solution

  • 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)