Domanda

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?

È stato utile?

Soluzione

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)

Altri suggerimenti

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'.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top