【问题标题】:Bash - subtract two hh:mm values [closed]Bash - 减去两个 hh:mm 值
【发布时间】:2021-12-20 10:30:33
【问题描述】:

我有两个变量被传递到一个函数中,它们是 HH:MM 格式的时间字符串。

我正在努力减去这两个变量

shop_opening_time=09:30
shop_closing_time=18:00
time_to_opening=$((current_time-shop_closing_time))
time_to_close=$((shop_opening_time-current_time))

请有人指导我如何减去这些? bash中有没有内置函数?

【问题讨论】:

  • 我投票结束这个问题,因为它属于 unix.stackexchange unix.stackexchange.com/a/490768
  • 谢谢@JatinMehrotra。很好的答案。该答案的唯一问题是关闭时间到打开时间的计算不正确。如果商店关门时间是 17:00,第二天早上 10 点开门,现在时间是 19:00,那么开门时间显示为 7 小时而不是 15 小时
  • 我不同意这与编程无关,但您应该至少展示您自己的尝试。简而言之,通常的解决方案是将值标准化为自纪元(UTC 1970 年 1 月 1 日午夜)以来的秒数,然后执行算术运算。但是您的值并不表示它们在哪一天;我们是否可以始终假设它们在相邻的日期,而开放时间在第二天?
  • 谢谢@tripleee。是的,这个假设是正确的。今天关门,明天开门。

标签: bash


【解决方案1】:

没有内置的 bash,但自己编写并不难:

#!/bin/bash
time_to() {
    local delta from_hh from_mm to_hh to_mm
    IFS=':' read from_hh from_mm to_hh to_mm <<< "$(date +%H:%M):$1"
    delta=$(((10#$to_hh * 60 + 10#$to_mm) - (10#$from_hh * 60 + 10#$from_mm)))
    [ $delta -lt 0 ] && ((delta += 1440))
#   printf '%d:%02d\n' $((delta/60)) $((delta%60))
    printf 'from %02d:%02d to %02d:%02d = %d:%02d\n' \
        $((10#$from_hh)) $((10#$from_mm)) \
        $((10#$to_hh)) $((10#$to_mm)) \
        $((delta/60)) $((delta%60))
}
time_to 09:30
from 13:49 to 09:30 = 19:41

time_to 18:00
from 13:49 to 18:00 = 4:11

【讨论】:

  • 谢谢@Fravadona
  • 能否解释一下代码中 10# 的用途
  • (( ))内,以0开头的数字被认为是八进制;为了确保它被解释为小数,我将基数设置为 10#
  • 你好 Fravadona - 你能帮我做另一个吗 - stackoverflow.com/questions/70430185/…
猜你喜欢
  • 1970-01-01
  • 2012-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-07
相关资源
最近更新 更多