Last active
October 25, 2025 22:30
-
-
Save danielsource/42257d7bb5ff2337303ac0197930bc74 to your computer and use it in GitHub Desktop.
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
| #!/bin/sh | |
| set -ef | |
| # About --date=STRING: https://www.gnu.org/software/coreutils/manual/html_node/General-date-syntax.html | |
| usage() { | |
| echo 'usage: datediff [-d|-h|-m|-s] [DATE1] DATE2' >&2 | |
| exit 1 | |
| } | |
| getdiff() { | |
| if [ $# -eq 1 ]; then | |
| d1="$(date +%s)" | |
| d2=$(date -d "$1" +%s) | |
| elif [ $# -eq 2 ]; then | |
| d1=$(date -d "$1" +%s) | |
| d2=$(date -d "$2" +%s) | |
| else | |
| usage | |
| fi | |
| diff=$((d2 - d1)) | |
| } | |
| case $1 in | |
| -d) shift; getdiff "$@"; echo $((diff / 86400)) ;; | |
| -h) shift; getdiff "$@"; echo $((diff / 3600)) ;; | |
| -m) shift; getdiff "$@"; echo $((diff / 60)) ;; | |
| -s) shift; getdiff "$@"; echo $diff ;; | |
| -*) usage ;; | |
| *) getdiff "$@" | |
| day=$((diff / 86400)) | |
| hour=$(((diff % 86400) / 3600)) | |
| min=$(((diff % 3600) / 60)) | |
| sec=$((diff % 60)) | |
| echo "$diff s = $day d + $hour h + $min min + $sec s" | |
| esac |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment