Take the 2-minute tour ×
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
1  
date "+(%H*60+%M)*60+%S" | bc –  groxxda Jul 25 at 13:42
    
echo $(($(date '+(%H*60+%M)*60+%S'))) –  groxxda Jul 25 at 13:59

2 Answers 2

up vote 8 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
now=$EPOCHSECONDS
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:

IFS=:
set -- $(date +%T)
echo "$(($1 * 3600 + $2 * 60 + $3))"
share|improve this answer
    
Very clever and good use of eval –  Ulrich Dangel Jul 25 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 ))
53983
share|improve this answer
2  
You want to make sure you don't do that at 23:59:59 –  Stéphane Chazelas Jul 25 at 13:02
    
And to convert back: date -d @$seconds –  choroba Jul 25 at 13:05

Your Answer

 
discard

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.