Shell: 如何比较两个时间字符串和 return 分钟的差异?
Shell: How to compare two Time strings and return difference in minutes?
我有两个时间字符串
current_utc_time=`date +"%H%M" -u`
output will be 0848
sch_time=`date +"18%M" -u`
output will be 1848
如何计算这两者之间的时差(以分钟为单位)?
t1=date +"%H%M" -u
t2=date +"18%M" -u
以秒为单位计算日期差异
让"tDiff=$t2-$t1"
计算大概的分钟差
让"hDiff=$tDiff/60"
将您的时间转换为纪元并计算秒数。我假设您不会从 date
获取时间,因为如果是这样,您只需使用 "+%s"
进行格式化即可立即获取纪元时间。答案假设您只有两个带有 %H%M
.
的字符串
因此,为您的字符串分配时间戳(小时和分钟)
current_utc_time=$(date +"%H%M")
sch_time=$(date +"18%M")
转换为 unix 时间戳。
macOS
epoch_current=$(date -j -f "%H%M" "$current_utc_time" +%s)
epoch_sch=$(date -j -f "%H%M" "$sch_time" +%s)
Linux
epoch_current=$(date --date "$current_utc_time" +%s)
epoch_sch=$(date --date "$sch_time" +%s)
计算差异(以分钟为单位)。
diff_in_minutes=$(( ($epoch_sch - $epoch_current) / 60 ))
我有两个时间字符串
current_utc_time=`date +"%H%M" -u`
output will be 0848
sch_time=`date +"18%M" -u`
output will be 1848
如何计算这两者之间的时差(以分钟为单位)?
t1=date +"%H%M" -u
t2=date +"18%M" -u
以秒为单位计算日期差异
让"tDiff=$t2-$t1"
计算大概的分钟差
让"hDiff=$tDiff/60"
将您的时间转换为纪元并计算秒数。我假设您不会从 date
获取时间,因为如果是这样,您只需使用 "+%s"
进行格式化即可立即获取纪元时间。答案假设您只有两个带有 %H%M
.
因此,为您的字符串分配时间戳(小时和分钟)
current_utc_time=$(date +"%H%M")
sch_time=$(date +"18%M")
转换为 unix 时间戳。
macOS
epoch_current=$(date -j -f "%H%M" "$current_utc_time" +%s)
epoch_sch=$(date -j -f "%H%M" "$sch_time" +%s)
Linux
epoch_current=$(date --date "$current_utc_time" +%s)
epoch_sch=$(date --date "$sch_time" +%s)
计算差异(以分钟为单位)。
diff_in_minutes=$(( ($epoch_sch - $epoch_current) / 60 ))