plhn
plhn

Reputation: 5273

Get remaining seconds from input HH:mm in bash (OSX)

I want write a simple bash script. Input is "HH:mm" string and the output is remaining seconds to that time, for example

$ getsec.sh 12:55 # now it's 12:30. so 25 minutes left.
1500

I thought using date command would probably the solution of this. But it seems like it doesn't exist the simple way that I can use.


(Added after checking some answers)

It looks like the date command depends on OS and version.
I use OSX, and the result of the suggested answer is as follows.

$ date -d '12:55' '+%s'
usage: date [-jnu] [-d dst] [-r seconds] [-t west] [-v[+|-]val[ymwdHMS]] ... 
            [-f fmt date | [[[mm]dd]HH]MM[[cc]yy][.ss]] [+format]

Upvotes: 0

Views: 51

Answers (3)

tripleee
tripleee

Reputation: 189507

The *BSD (and thus OSX) date command has a different option syntax than GNU date, which is ubiquitous on Linux and available on many other platforms (including OSX, with Homebrew, Fink, etc).

now=$(date -j +%s)
then=$(date -j -f '%H:%M' 12:55 +%s)
echo "$((then-now)) seconds left"

For a portable solution, maybe use a portable scripting language instead.

Upvotes: 2

the_velour_fog
the_velour_fog

Reputation: 2184

This script accepts the target time as a command line argument (accessed in the script as the parameter $1

#!/bin/bash

current_time=$(date +%s)
target_time=$(date +%s --date="$1")

# evaluate the difference using an arithmetic expression
echo "seconds remaining to target time: "$(( target_time - current_time ))

usage:

% ./get_sec.sh "22:00"

output:

seconds remaining to target time: 16151 

Upvotes: 1

anubhava
anubhava

Reputation: 785316

You can do:

ts=$(date -d '12:55' '+%s')
now=$(date '+%s')

diff=$((ts-now))

Upvotes: 1

Related Questions