Bash脚本:两分之间的差异 [英] Bash script: difference in minutes between two times

查看:199
本文介绍了Bash脚本:两分之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个时间字符串;例如。 09:11和17:22在同一天(格式为hh:mm)。如何计算这两者之间的时差?



标准日期库是否可以执行此操作?



示例:

 #!/ bin / bash 

MPHR = 60分钟每小时。

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

#通过使用读取和拆分IFS
IFS =:read old_hour old_min<<< $ old
IFS =:读取小时最小值<<< $ new

#转换小时到分钟
#10#是避免错误的前导零
#通过告诉bash我们使用基础10
total_old_minutes = $((10#$ old_hour * 60 + 10#$ old_min))
total_minutes = $((10#$ hour * 60 + 10#$ min))

echo差别是$((total_minutes - total_old_minutes))分钟

另一个使用日期(我们使用小时/分钟,所以日期不重要)

  old = 09:11 
new = 17:22

IFS =:read old_hour old_min<<<< $ old
IFS =:读取小时最小值<<< $ new

#从Unix EPOCH时间转换日期1970-01-01小时:分:00秒
sec_old = $(日期-d1970-01- 01 $ old_hour:$ old_min:00+%s)
sec_new = $(date -d1970-01-01 $ hour:$ min:00+%s)

差异是$(((sec_new - sec_old)/ 60))分钟

a href =http://en.wikipedia.org/wiki/Unix_time =noreferrer> http://en.wikipedia.org/wiki/Unix_time


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 standard date library do this?

Example:

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

Is there a simpler way of doing this given the hour and minute in hh:mm

解决方案

A pure 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

这篇关于Bash脚本:两分之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆