Bash script: difference in minutes between two times

前端 未结 7 1590
不思量自难忘°
不思量自难忘° 2020-12-31 07:55

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

相关标签:
7条回答
  • 2020-12-31 08:24

    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

    0 讨论(0)
提交回复
热议问题