2

2 つの日付 (週末を除く) 間の日差を検索するのと同じ問題ですが、これは JavaScript の場合です。Unix(KSH)でそれを行う方法は?

4

2 に答える 2

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
于 2012-04-20T08:20:18.053 に答える
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
于 2012-09-13T20:53:26.977 に答える