如何找到Unix中两个日期时间(周末日除外)之间的差异?

时间:2012-04-20 06:41:15

标签: unix ksh

Find day difference between two dates (excluding weekend days)相同的问题,但它适用于javascript。如何在Unix(KSH)中做到这一点?

2 个答案:

答案 0 :(得分:1)

这是我的Bash脚本,我认为在Ksh中它会是类似的。

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

我的测试数据:

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

测试脚本:

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

答案 1 :(得分: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