Compare days with 2 dates
1. Script reference
Script 1:
#!/bin/bash#格式化过期日期,格式化过期日期完整时间以当前时间作为参考!expday="2018-04-11 `date +%T`"echo "Expire day is $expday"#当前日期时间格式为stamp时间戳todays=`date +%s`echo "Today is $(date +"%F %T")"#以下2种方式做时间的四则运算,分别使用 let 或者 $(( ))#过期日期已格式化,规避整数运算的误差(去余数)#let dayDiff=($(date -d "$expday" +%s)-$todays)/86400dayDiff=$(( ($(date -d "$expday" +%s)-$todays)/86400 ))echo "Diff day is $dayDiff days!"
Other Notes:
Bash does not support floating-point operations, and if floating-point operations are required, Bc,awk processing is required.
Script 2:
A method that supports floating-point arithmetic and calculates the exact number of days:
#!/bin/bash#不用刻意格式化过期日,默认时间 00:00:00expday="2018-04-11"echo "Expire day is $expday"todays=`date +%s`echo "Today is $(date +"%F %T")"#仅输出计算公式,管道输出给bc进行浮点运算#scale控制小数位数dayDiff=`echo "scale=2;($(date -d "$expday" +%s)-$todays)/86400"|bc`echo "Diff day is $dayDiff days!"
2. Floating-point comparison method:
——————————————————————————
if [ $(echo "1.8 < 15" | bc) = 1 ];thenecho Trueelseecho Falsefi
3. Direct comparison of dates using the date command
3day=$(date -d "$Expday -3 day" %F)2day=$(date -d "$Expday -2 day" %F)
Shell Scripting-date comparison and judgment