0

我正在拼命地寻找一个 bash 或 ksh 例程,它可以让我找到例如今天日期之前的前一个星期一、星期二、星期三……。另外,它必须在普通的 Solaris X 上工作,而且我没有可用的 GNU 日期。

例如:今天 = 2013/01/17 星期四;假设我想找到最后一个星期一。它必须返回:2013/01/14

我设法在网上找到了一个脚本,它可以完美地完成所有日子的工作,除了在这种特定情况下:例如:Today = Thursday 2013/01/17; 我想找到最后一个星期四,结果应该是: 2013/01/10 ;但相反,我又得到了今天的约会。

使用的脚本是这样的:

#!/bin/ksh

#Get the nbr of the current weekday (1-7)
DATEWEEK=`date +"%u"`
#Which previous weekday will we need (1-7)
WEEKDAY=$1
# Main part
#Get current date
DAY=`date +"%d"`
MONTH=`date +"%m"`
YEAR=`date +"%Y"`
#Loop trough the dates in the past
COUNTER=0
if [[ $DATEWEEK -eq $WEEKDAY ]] ; then
# I need to do something special for the cases when I want to find the date of the same day last week
  DAYS_BACK=168
  DAY=`TZ=CST+$DAYS_BACK date +%d`
  echo "DAY (eq) = $DAY"
else
    while [[ $DATEWEEK -ne $WEEKDAY ]] ; do
       COUNTER=`expr $COUNTER + 1`
       echo "Counter is: $COUNTER"
       DAYS_BACK=`expr $COUNTER \* 24`
       echo "DAYS BACK is: $DAYS_BACK"
       DAY=`TZ=CST+$DAYS_BACK date +%d`
       echo "DAY is: $DAY"
        if [[ "$DAY" -eq 0 ]] ; then
         MONTH=`expr "$MONTH" - 1`
           if [[ "$MONTH" -eq 0 ]] ; then
            MONTH=12
           YEAR=`expr "$YEAR" - 1`
           fi
         fi
       DATEWEEK=`expr $DATEWEEK - 1`
     if [[ $DATEWEEK -eq 0 ]]; then
     DATEWEEK=7
     fi
done
fi
echo $DAY/$MONTH/$YEAR
4

2 回答 2

0

(我之前的建议并没有像我想象的那样奏效。昨晚已经很晚了……)

关键是今天忽略,但仍然循环。试试这样:

#!/bin/ksh

#Get the nbr of the current weekday (1-7)
DATEWEEK=`date +"%u"`
#Which previous weekday will we need (1-7)
WEEKDAY=$1
# Main part
#Get current date
DAY=`date +"%d"`
MONTH=`date +"%m"`
YEAR=`date +"%Y"`
#Loop trough the dates in the past
COUNTER=0
while [ $COUNTER -eq 0 ] || [[ $DATEWEEK -ne $WEEKDAY ]] ; do
   COUNTER=`expr $COUNTER + 1`
   echo "Counter is: $COUNTER"
   DAYS_BACK=`expr $COUNTER \* 24`
   echo "DAYS BACK is: $DAYS_BACK"
   DAY=`TZ=CST+$DAYS_BACK date +%d`
   echo "DAY is: $DAY"
   if [[ "$DAY" -eq 0 ]] ; then
       MONTH=`expr "$MONTH" - 1`
       if [[ "$MONTH" -eq 0 ]] ; then
           MONTH=12
           YEAR=`expr "$YEAR" - 1`
       fi
   fi
   DATEWEEK=`expr $DATEWEEK - 1`
   if [[ $DATEWEEK -eq 0 ]]; then
       DATEWEEK=7
   fi
done
echo $DAY/$MONTH/$YEAR

不过,你的DAY=`TZ=CST+$DAYS_BACK date +%d`把戏对我不起作用。Linuxdate似乎总有一天能做到这一点。

于 2013-01-17T22:29:12.677 回答
0

这行得通吗?

today=$(date +"%u")
weekday=$1
curdate=$(date +"%s")
gobackdays=$(($today - $weekday))
if [ $gobackdays -le 0 ]; then
  let gobackdays+=7
fi
SECSDAY=86400
backtime=$(($curdate - $gobackdays * $SECSDAY))
echo $(date -d "@$backtime")
于 2013-01-18T11:16:36.380 回答