Last active
July 13, 2016 18:52
-
-
Save bezhermoso/2d61cf44646c2f07c0820d81c644c1de to your computer and use it in GitHub Desktop.
Calculate time duration in bash (only for OS X's `date`. Probably won't work with out UNIX/Linux distros)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# Usage: `calctime <start> <end>` i.e. `calctime 08:20 11:22`. | |
# Will prompt for start time and end time if not provided. | |
# DON'T specify AM or PM. Support is still @todo. | |
# However, this will try its best to guess the proper duration i.e. `calctime 08:00 1:00` will print out `Duration: 5 hours`. | |
from=$1 | |
to=$2 | |
if [[ -z $from ]]; then | |
read -p "From: " from | |
read -p "To: " to | |
fi | |
IFS=: read from_hr from_min <<< "$from" | |
IFS=: read to_hr to_min <<< "$to" | |
secs_from=$(date -j -f "%D %T" "01/01/70 $from_hr:$from_min:00" +%s) | |
secs_to=$(date -j -f "%D %T" "01/01/70 $to_hr:$to_min:00" +%s) | |
diff=$(($secs_to-$secs_from)) | |
if [[ $diff -lt 0 ]]; then | |
secs_to=$(date -j -f "%D %T" "01/01/70 $(($to_hr+12)):$to_min:00" +%s) | |
diff=$((secs_to-$secs_from)) | |
fi | |
hours=$(echo "scale=2; ($diff) / (60 * 60)" | bc) | |
echo "Duration: $hours hours" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment