Search code examples
bashshellunixshunix-timestamp

Calculate difference in months between two dates in Unix?


I have two variables in the format 'YYYYMM'

DATE1=201712
DATE2=201801

How do I calculate the difference between these two date variables in months in unix?


Solution

  • How about:

    #!/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