计算Unix中两个日期之间的差异?

时间:2018-01-30 06:42:14

标签: bash shell unix sh unix-timestamp

我有两个变量格式为' YYYYMM'

DATE1=201712
DATE2=201801

如何在unix中计算这两个日期变量之间的差异?

2 个答案:

答案 0 :(得分:3)

怎么样:

#!/bin/bash

DATE1=201712
DATE2=201801

y1=${DATE1:0:4}
m1=${DATE1:4:2}

y2=${DATE2:0:4}
m2=${DATE2:4:2}

diff=$(( ($y2 - $y1) * 12 + (10#$m2 - 10#$m1) ))
echo $diff

答案 1 :(得分:1)

我准备了以下bash功能,如果清楚的话,请告诉我:

#!/usr/bin/env bash

DATE1=201712
DATE2=201801

function dateDiffMonth() {
    local y1=$(date -d "$1""01" '+%Y') # extract the year from your date1
    local y2=$(date -d "$2""01" '+%Y') # extract the year from your date2
    local m1=$(date -d "$1""01" '+%m') # extract the month from your date1
    local m2=$(date -d "$2""01" '+%m') # extract the month from your date2
    echo $(( ($y2 - $y1) * 12 + (10#$m2 - 10#$m1) )) #compute the months difference 12*year diff+ months diff -> 10# force the shell to interpret the following number in base-10
}

RESULT=`dateDiffMonth $DATE1 $DATE2`
echo "there is a gap of $RESULT months betwen $DATE2 and $DATE1"