我有两个时间字符串;例如。同一天的“ 09:11”和“ 17:22”(格式为hh:mm)。如何计算这两者之间的时间差(以分钟为单位)?
标准date库可以这样做吗?
date
例:
#!/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 ))
给定hh:mm中的小时和分钟,是否有更简单的方法来执行此操作
一个纯bash解决方案:
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"
使用的另一种解决方案date(我们使用小时/分钟,因此日期并不重要)
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"
参见http://en.wikipedia.org/wiki/Unix_time