how to find the difference b/w to dates stored in a variable in shell script ( KSH shell )

StackOverflow https://stackoverflow.com/questions/16229324

  •  13-04-2022
  •  | 
  •  

Question

In hp-ux as there is no GNU date available, i.e the -d and -s options of the date command are not available. How do I find the difference between two given dates in days (as we do in Solaris or bash shell)?

Was it helpful?

Solution

There are actually many solutions to be found via Google, but here is one that I just stumbled across and like for its brevity. You would use its ansi_dn function on both dates and calculate the difference.

diff_dates.sh:

#!/bin/ksh

. ./ansi_dn.sh

date_to="$1"
date_from="$2"

echo $((
      $(ansi_dn \
        $(echo "${date_to}"   | cut -d/ -f3) \
        $(echo "${date_to}"   | cut -d/ -f2) \
        $(echo "${date_to}"   | cut -d/ -f1) \
      )
    - $(ansi_dn \
        $(echo "${date_from}" | cut -d/ -f3) \
        $(echo "${date_from}" | cut -d/ -f2) \
        $(echo "${date_from}" | cut -d/ -f1) \
      )
))

(If you have the years, months and days of both dates in separate variables already the cut nightmare is not needed, obviously.)

Example:

$ ./diff_dates.sh 08/05/2013 01/01/1939
27156

Let's verify correctness with GNU date:

$ echo $(( ( $(date -d 2013-05-08 +%s) - $(date -d 1939-01-01 +%s) + 43200 ) / 86400))
27156
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top