我目前有以下变量,想知道以秒为单位的时间量。所以CURRENT_TIME-TEST_START
TEST_START=$(date '+%d/%m/%Y %H:%M:%S')
sleep 4
CURRENT_TIME=$(date '+%d/%m/%Y %H:%M:%S')
我在下面尝试过,但仍继续受到非法行为
START_IN_SECONDS=$(date --date "$(TEST_START)" +%s)
这是在Mac中。
答案 0 :(得分:0)
#!/bin/bash
# Time Arithmetic
TIME1=05:36:11
TIME2=06:46:00
# Convert the times to seconds from the Epoch
SEC1=`date +%s -d ${TIME1}`
SEC2=`date +%s -d ${TIME2}`
# Use expr to do the math, let's say TIME1 was the start and TIME2 was the finish
DIFFSEC=`expr ${SEC2} - ${SEC1}`
echo Start ${TIME1}
echo Finish ${TIME2}
echo Took ${DIFFSEC} seconds.
# And use date to convert the seconds back to something more meaningful
echo Took `date +%H:%M:%S -ud @${DIFFSEC}`
输出:
Start 05:36:11
Finish 06:46:00
Took 4189 seconds.
Took 01:09:49
答案 1 :(得分:0)
首先,用于扩展变量的语法为$variable
或${variable}
,而不是$(variable)
。
第二,date
不知道如何解析%d/%m/%Y
格式的日期。当日期使用斜杠时,它期望它是%m/%d/%Y
。因此,请更改您的前两行以使用正确的格式。
TEST_START=$(date '+%m/%d/%Y %H:%M:%S')
sleep 4
CURRENT_TIME=$(date '+%m/%d/%Y %H:%M:%S')
START_IN_SECONDS=$(date --date "$TEST_START" +%s)
CURRENT_IN_SECONDS=$(date --date "$CURRENT_TIME" +%s)
diff=$((CURRENT_IN_SECONDS - START_IN_SECONDS))
echo $diff
当然,您可以直接使用xxx_IN_SECONDS
设置+%s
变量,而不用解析格式化的日期:
START_IN_SECONDS=$(date +%s)
sleep 4
CURRENT_IN_SECONDS=$(date +%s)