The same problem to Find day difference between two dates (excluding weekend days) but it is for javascript. How to do that in Unix (KSH)?
Asked
Active
Viewed 4,390 times
2
-
Why have you duplicated the question? – Pavan Manjunath Apr 20 '12 at 07:11
-
This is not duplicated, no i need this script for unix in korn shell it wont work – user1345801 Apr 20 '12 at 07:13
-
I have code to find how many days between dates. bue i need to skip the weekends from there days. For example 20-4-2012 to 24-4-2012 have 4 days but 21st and 22nd's are week ends so i need result as 2. – user1345801 Apr 20 '12 at 07:59
2 Answers
1
Here is my Bash script, I think in Ksh it will be similar.
#! /bin/bash
#Usage dateDiff startDate endDate
startDate="$1 00:00:00"
endDate="$2 tomorrow 00:00:00" #tomorrow to include both days
stampEnd=`date -d "$endDate" +%s`
stampStart=`date -d "$startDate" +%s`
#difference in calendar days
daysDiff=`echo "($stampEnd - $stampStart) / (60 * 60 * 24)" | bc`;
#week day
weekDay=`date -d "$endDate" +%u`;
weekEndsLastWeek=`echo "$weekDay - 6" | bc`;
if test $weekEndsLastWeek -lt 0; then
weekEndsLastWeek=0;
fi
if test $weekEndsLastWeek -gt $daysDiff; then
weekEndsLastWeek=$daysDiff
fi
#normalize - make endDate a Sunday
if test $weekDay -ne 1; then #if not a Sunday already
daysDiffSunday=`echo "$daysDiff - ($weekDay - 1)" | bc`;
else
daysDiffSunday=$daysDiff;
fi
firstWeekends=0;
weekends=0;
if test $daysDiffSunday -ge 0; then
firstWeekends=`echo "$daysDiffSunday % 7" | bc`;
if test $firstWeekends -gt 2; then
firstWeekends=2
fi
weekends=`echo "$daysDiffSunday / 7 * 2" | bc`;
fi;
echo "$daysDiff - $weekends - $firstWeekends - $weekEndsLastWeek" | bc
My test data:
04/20/2012 04/22/2012 1
04/20/2012 04/25/2012 4
04/20/2012 04/30/2012 7
04/20/2012 04/28/2012 6
04/18/2012 04/21/2012 3
04/18/2012 04/22/2012 3
04/14/2012 04/21/2012 5
04/14/2012 04/22/2012 5
04/15/2012 04/21/2012 5
04/15/2012 04/22/2012 5
Test script:
allPassed=1
while read line; do
set $line;
result=`./dateDiff $1 $2`;
expected="$3";
if test "$result" -ne "$expected"; then
echo "Error in test $line: expected $expected, result $result" 1>&2
allPassed=0
fi;
done
if test $allPassed -eq 1; then
echo "All tests passed";
fi

Aleksey Otrubennikov
- 1,121
- 1
- 12
- 26
0
#/bin/ksh
DATE1="2005-09-01"
DATE2="2011-02-20"
typeset -L4 y1 y2
typeset -Z -R2 m d
y1=$DATE1
y2=$DATE2
c=0
while [[ $y1 -le $y2 ]]
do
for m in 1 2 3 4 5 6 7 8 9 10 11 12
do
for d in $(cal $m $y1)
do
[[ "${d# }" < "A" ]] && {
(( c = c + 1 ))
[[ "$y1-$m-$d" = "$DATE1" ]] && d1=$c
[[ "$y1-$m-$d" = "$DATE2" ]] && {
d2=$c
break;
}
}
done
done
(( y1 = y1 + 1 ))
done
(( days = d2 - d1 ))
echo $days

rdr
- 1
- 1