计算 Unix 中两个日期之间的月差?
Calculate difference in months between two dates in Unix?
我有两个格式为 'YYYYMM'
的变量
DATE1=201712
DATE2=201801
如何在 unix 中计算这两个日期变量之间的月差?
怎么样:
#!/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
我准备了下面的bash函数给大家看清楚了告诉我:
#!/usr/bin/env bash
DATE1=201712
DATE2=201801
function dateDiffMonth() {
local y1=$(date -d """01" '+%Y') # extract the year from your date1
local y2=$(date -d """01" '+%Y') # extract the year from your date2
local m1=$(date -d """01" '+%m') # extract the month from your date1
local m2=$(date -d """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"
我有两个格式为 'YYYYMM'
的变量DATE1=201712
DATE2=201801
如何在 unix 中计算这两个日期变量之间的月差?
怎么样:
#!/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
我准备了下面的bash函数给大家看清楚了告诉我:
#!/usr/bin/env bash
DATE1=201712
DATE2=201801
function dateDiffMonth() {
local y1=$(date -d """01" '+%Y') # extract the year from your date1
local y2=$(date -d """01" '+%Y') # extract the year from your date2
local m1=$(date -d """01" '+%m') # extract the month from your date1
local m2=$(date -d """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"