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

Thanks

Richard.

link|improve this question

50% accept rate
feedback

5 Answers

up vote 25 down vote accepted

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)

link|improve this answer
2  
I wonder how many ms the cut adds :-) – Kyle Brandt Jun 14 '10 at 16:23
you're looking at screen refresh time - that's already going to add something :) – warren Jun 14 '10 at 16:32
I think seconds * 1000 will be fine :) – Richard Jun 14 '10 at 16:34
4  
Or if you want to do it all in the shell, avoiding the expensive overhead of an additional process (actually, we're avoiding the problem when the number of digits in %+s+N changes): echo $(($(date +%s%N)/1000)) – MikeyB Jun 14 '10 at 16:38
@MikeyB - when will the number of digits change? we're only in the single digit billions for seconds now.. which means at least another 7x40 years before it'd be something to worry about, no? (Presuming, of course, we don't hit the Unix time wall first) – warren Jun 14 '10 at 17:48
show 2 more comments
feedback

Just throwing this out there, but I think the correct formula with the division would be:

echo $(($(date +%s%N)/1000000))
link|improve this answer
feedback

Here is how to get time in milliseconds without performing division. Maybe it's faster...

# test=`date +%s%N`
# testnum=${#test}
# echo ${test:0:$testnum-6}
1297327781715
link|improve this answer
Another alternative in pure bash that works only with bash 4.2+ is same as above but use printf to get the date. It will definitely be faster because no processes are forked off the main one. printf -v test '%(%s%N)T' -1 testnum=${#test} echo ${test:0:$testnum-6} Another catch here is that your strftime implementation should support %s and %N which is NOT the case on my test machine with bash 4.2. – akostadinov Sep 9 '11 at 9:36
feedback

Unfortunately I only seem to be able to add new answers, not comment, but I think it's worth noting that the man asked for Unix, not Linux, and the current top answer (date +%s%N) doesn't work on my AIX system.

link|improve this answer
+1 Same for OS X, and FreeBSD – slomojo May 19 at 0:28
feedback

My solution is not the best but worked for me.

date +%s000

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

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.