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?

有帮助吗?

解决方案

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)

其他提示

You can also use mod instead of an explicit date difference. So for example, with 1 second resolution:

millis_since_midnight=$[1000 * ( ( `date "+%s"` - 28800 ) % 86400 )]

Note that 28800 is the PST offset from UTC in seconds. This kludge was useful for me on systems like OSX that have BSD time and thus lack the ability to specify --date 'today 00:00:00'.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top