Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script: difference in minutes between two times

I have two time strings; eg. "09:11" and "17:22" on the same day (format is hh:mm). How do I calculate the time difference in minutes between these two?

Can the standard date library do this?

Example:

#!/bin/bash

MPHR=60    # Minutes per hour.

CURRENT=$(date -u -d '2007-09-01 17:30:24' '+%F %T.%N %Z')
TARGET=$(date -u -d'2007-12-25 12:30:00' '+%F %T.%N %Z')

MINUTES=$(( $(diff) / $MPHR ))

Is there a simpler way of doing this given the hour and minute in hh:mm

like image 609
gorn Avatar asked Jan 13 '13 22:01

gorn


People also ask

How does bash script calculate time elapsed?

Measure Elapsed Time in Milliseconds in Bash To measure elapsed time with millisecond resolution, use date with +%s. %3N option, which returns the current time in milliseconds.

How do I see time in Bash?

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


2 Answers

I would convert the dates to UNIX timestamps; you can subtract to get the difference in seconds, then divide by 60:

#!/bin/bash

MPHR=60    # Minutes per hour.

CURRENT=$(date +%s -d '2007-09-01 17:30:24')
TARGET=$(date +%s -d'2007-12-25 12:30:00')

MINUTES=$(( ($TARGET - $CURRENT) / $MPHR ))
like image 20
chepner Avatar answered Oct 06 '22 00:10

chepner


A pure bash solution :

old=09:11
new=17:22

# feeding variables by using read and splitting with IFS
IFS=: read old_hour old_min <<< "$old"
IFS=: read hour min <<< "$new"

# convert hours to minutes
# the 10# is there to avoid errors with leading zeros
# by telling bash that we use base 10
total_old_minutes=$((10#$old_hour*60 + 10#$old_min))
total_minutes=$((10#$hour*60 + 10#$min))

echo "the difference is $((total_minutes - total_old_minutes)) minutes"

Another solution using date (we work with hour/minutes, so the date is not important)

old=09:11
new=17:22

IFS=: read old_hour old_min <<< "$old"
IFS=: read hour min <<< "$new"

# convert the date "1970-01-01 hour:min:00" in seconds from Unix EPOCH time
sec_old=$(date -d "1970-01-01 $old_hour:$old_min:00" +%s)
sec_new=$(date -d "1970-01-01 $hour:$min:00" +%s)

echo "the difference is $(( (sec_new - sec_old) / 60)) minutes"

See http://en.wikipedia.org/wiki/Unix_time

like image 55
Gilles Quenot Avatar answered Oct 06 '22 00:10

Gilles Quenot