Bash script: difference in minutes between two times Bash script: difference in minutes between two times bash bash

Bash script: difference in minutes between two times


A pure solution :

old=09:11new=17:22# feeding variables by using read and splitting with IFSIFS=: 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 10total_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:11new=17:22IFS=: 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 timesec_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


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

#!/bin/bashMPHR=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 ))


Here is how I did it:

START=$(date +%s);sleep 1; # Your stuffEND=$(date +%s);echo $((END-START)) | awk '{printf "%d:%02d:%02d", $1/3600, ($1/60)%60, $1%60}'

Really simple, take the number of seconds at the start, then take the number of seconds at the end, and print the difference in minutes:seconds.