6

How do I find the number of seconds till midnight of current day?

4
  • Doens't that rather belong to stackoverflow?
    – Benoit
    Mar 16 '11 at 15:14
  • @Benoit : I considered that, but decided against because I thought that this would be scripting, not programming.
    – bguiz
    Mar 16 '11 at 23:02
  • Warning: you are trying to do interval arithmetic with absolute times of day. Think carefully about what happens around DST transitions.
    – PhilR
    May 18 '11 at 14:00
  • @Phil : Yup, a solution which takes DST (and other corner cases) would be ideal
    – bguiz
    May 23 '11 at 13:02
8

What about:

echo $(($(date -d "$(date +00:00-24:00)" +%s)-$(date +%s)))
2
  • 2
    What does date +00:00-24:00 do? Aug 15 '19 at 7:01
  • Yeah, the man page doesn't give any clues.
    – e40
    Oct 21 '20 at 19:29
5

If you have a version of date that supports it:

echo $(($(date -d 23:59:59 +%s) - $(date +%s) + 1))

or

echo $(($(date -d 'tomorrow 00:00:00' +%s) - $(date +%s)))
1
  • first one seems better from a computational efficiency perspective
    – Otheus
    Feb 5 '16 at 11:52
0

If you want a solution which works always try this:

$((`date +%s` % 86400 + $OFFSET ))

The $OFFSET should be the difference in seconds between the local timezone and UTC.

1
  • Does this work at the transition of winter/summer time (... wasting time)? Aug 15 '19 at 7:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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