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)
-
Epoch format ? number of second since 1/1/1970 ?Archemar– Archemar2015-10-12 14:12:23 +00:00Commented Oct 12, 2015 at 14:12
-
Yes Archemar... no. of seconds since 1/1/1970.ajain– ajain2015-10-12 14:16:48 +00:00Commented Oct 12, 2015 at 14:16
-
7Possible duplicate: Tool in UNIX to subtract datesMarco– Marco2015-10-12 14:23:26 +00:00Commented Oct 12, 2015 at 14:23
-
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.Archemar– Archemar2015-10-12 14:24:46 +00:00Commented Oct 12, 2015 at 14:24
-
github.com/hroptatyr/dateutils is the best bet so far.Deer Hunter– Deer Hunter2015-10-12 14:42:11 +00:00Commented Oct 12, 2015 at 14:42
Add a comment
|
2 Answers
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
-
This resets months count each yearDani_l– Dani_l2015-10-12 15:29:36 +00:00Commented Oct 12, 2015 at 15:29
-
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-%H12-31-19Jay Imerman– Jay Imerman2021-12-07 13:52:43 +00:00Commented Dec 7, 2021 at 13:52
#!/bin/bash
d=(60sec 60min 24hours 30days 12month 1000year)
i=0
while [ $1 -ge ${d[i]%%[a-z]*} ]
do
set -- $(($1/${d[i]%%[a-z]*})) $(($1%${d[i]%%[a-z]*})) ${d[i]##*[0-9]} ${*:2}
((i++))
done
echo $1 ${d[i]##*[0-9]} ${*:2}