How do I get the current Unix time in milliseconds in Bash?

How do I get the current Unix time in milliseconds (i.e number of milliseconds since Unix epoch January 1 1970)?


Solution 1:

This:

date +%s 

will return the number of seconds since the epoch.

This:

date +%s%N

returns the seconds and current nanoseconds.

So:

date +%s%N | cut -b1-13

will give you the number of milliseconds since the epoch - current seconds plus the left three of the nanoseconds.


and from MikeyB - echo $(($(date +%s%N)/1000000)) (dividing by 1000 only brings to microseconds)

Solution 2:

You may simply use %3N to truncate the nanoseconds to the 3 most significant digits (which then are milliseconds):

$ date +%s%3N
1397392146866

This works e.g. on my Kubuntu 12.04 (Precise Pangolin).

But be aware that %N may not be implemented depending on your target system. E.g. tested on an embedded system (buildroot rootfs, compiled using a non-HF ARM cross toolchain) there was no %N:

$ date +%s%3N
1397392146%3N

(And also my (non rooted) Android tablet doesn't have %N.)

Solution 3:

date +%N doesn't work on OS X, but you could use one of

  • Ruby: ruby -e 'puts Time.now.to_f'
  • Python: python -c 'import time; print(int(time.time() * 1000))'
  • Node.js: node -e 'console.log(Date.now())'
  • PHP: php -r 'echo microtime(TRUE);'
  • Elixir: DateTime.utc_now() |> DateTime.to_unix(:millisecond)
  • The Internet: wget -qO- http://www.timeapi.org/utc/now?\\s.\\N
  • or for milliseconds rounded to nearest second date +%s000

Solution 4:

My solution is not the best, but it worked for me:

date +%s000

I just needed to convert a date like 2012-05-05 to milliseconds.