Shell Scripting-date comparison and judgment

Source: Internet
Author: User
Tags diff

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.