Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux date command, finding seconds to next hour

Tags:

date

linux

bash

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

like image 322
broccoli Avatar asked Dec 22 '14 02:12

broccoli


People also ask

How do I get seconds in Linux?

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.

What is date +% s in Bash?

date +%S. Displays seconds [00-59] date +%N. Displays in Nanoseconds. date +%T.

How do I echo date and time in Linux?

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 # ...


1 Answers

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 way

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.

like image 85
kojiro Avatar answered Sep 28 '22 10:09

kojiro