How do I find the seconds to the next hour using date? I know I can do
date -d "next hour"
but that just adds 1 hour to the present time. I want it to show the seconds to the next full hour. For example if the current time is 9:39am
I want to find the number of seconds to 10am
The %s option calculates unix timestamp by finding the number of seconds between the current date and unix epoch. You will get a different output if you run the above date command. You can use the -d option to the date command for converting the unix timestamp to date.
date +%S. Displays seconds [00-59] date +%N. Displays in Nanoseconds. date +%T.
Sample shell script to display the current date and time #!/bin/bash now="$(date)" printf "Current date and time %s\n" "$now" now="$(date +'%d/%m/%Y')" printf "Current date in dd/mm/yyyy format %s\n" "$now" echo "Starting backup at $now, please wait..." # command to backup scripts goes here # ...
The epoch timestamp of right now is
now=$(date '+%s')
That of the next hour is
next=$(date -d $(date -d 'next hour' '+%H:00:00') '+%s')
The number of seconds until the next hour is
echo $(( next - now ))
For a continuous solution, use functions:
now() { date +%s; }
next() { date -d $(date -d "next ${1- hour}" '+%H:00:00') '+%s'; }
And now you have
echo $(( $(next) - $(now) ))
and even
echo $(( $(next day) - $(now) ))
Another slightly mathier approach still uses the epoch timestamp. We know it started on an hour, so the timestamp mod 3600 only equals zero on the hour. Thus
$(( $(date +%s) % 3600 ))
is the number of seconds since the last hour, and
$(( 3600 - $(date +%s) % 3600 ))
is the number of seconds until the next.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With