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, 2011 at 15:14
  • @Benoit : I considered that, but decided against because I thought that this would be scripting, not programming.
    – bguiz
    Mar 16, 2011 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, 2011 at 14:00
  • @Phil : Yup, a solution which takes DST (and other corner cases) would be ideal
    – bguiz
    May 23, 2011 at 13:02

3 Answers 3

8

What about:

echo $(($(date -d "$(date +00:00-24:00)" +%s)-$(date +%s)))
3
  • 2
    What does date +00:00-24:00 do? Aug 15, 2019 at 7:01
  • Yeah, the man page doesn't give any clues.
    – e40
    Oct 21, 2020 at 19:29
  • This one is definitely giving me the wrong answer. Nov 7, 2021 at 19:28
6

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, 2016 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, 2019 at 7:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .