Subtract two dates using Shell Scripting

10,501

Try something like this:

#!/bin/bash

d1=`date -d 20140929 +%s`
d2=`date -d 20001115 +%s`

date --date=@$(($d1 - $d2)) +'%m months, %d days, %H hours'

Output:

11 months, 15 days, 02 hours
Share:
10,501

Related videos on Youtube

ajain
Author by

ajain

Updated on September 18, 2022

Comments

  • ajain
    ajain almost 2 years

    How can I subtract two dates in epoch format using Shell Scripting. I want the output in Months, Days, Hours format. Also It should work even for more than 12 months ( as I came across few which were resetting to 0 months if more than 12)

    • Арсений Черенков
      Арсений Черенков over 8 years
      Epoch format ? number of second since 1/1/1970 ?
    • ajain
      ajain over 8 years
      Yes Archemar... no. of seconds since 1/1/1970.
    • Marco
      Marco over 8 years
      Possible duplicate: Tool in UNIX to subtract dates
    • Арсений Черенков
      Арсений Черенков over 8 years
      didn't it depends on starting date ? 29 days from Jan,31 to Mar,1st (and one month), 29 days from July,1 to July,30 and zero month.
    • Deer Hunter
      Deer Hunter over 8 years
      github.com/hroptatyr/dateutils is the best bet so far.
  • Dani_l
    Dani_l over 8 years
    This resets months count each year
  • Jay Imerman
    Jay Imerman over 2 years
    Yeah, this doesn't work. Here's what I get: d1="03/26/2022" d2=$(date +%m/%d/%Y) date --date=@$(($d1 - $d2)) +%m-%d-%H 12-31-19