Sign up ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Using the date program, how can I calculate the number of seconds since midnight?

share|improve this question
date "+(%H*60+%M)*60+%S" | bc –  groxxda Jul 25 '14 at 13:42
echo $(($(date '+(%H*60+%M)*60+%S'))) –  groxxda Jul 25 '14 at 13:59

2 Answers 2

up vote 9 down vote accepted

To avoid race conditions, still assuming GNU date:

eval "$(date +'today=%F now=%s')"
midnight=$(date -d "$today 0" +%s)
echo "$((now - midnight))"

With zsh, you can do it internally:

zmodload zsh/datetime
strftime -s today %F $now
strftime -rs midnight %F $today
echo $((now - midnight))

Portably, in timezones where there's no daylight saving switch, you could do:

set -- $(date +%T)
echo "$(($1 * 3600 + $2 * 60 + $3))"
share|improve this answer
Very clever and good use of eval –  Ulrich Dangel Jul 25 '14 at 13:14

Based on bash, get current time in milliseconds since midnight, on a GNU system, it can be done like this:

$ now=$(date '+%s')
$ midnight=$(date -d 'today 00:00:00' '+%s')
$ echo $(( now - midnight ))
share|improve this answer
You want to make sure you don't do that at 23:59:59 –  Stéphane Chazelas Jul 25 '14 at 13:02
And to convert back: date -d @$seconds –  choroba Jul 25 '14 at 13:05

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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