On Mon, May 30, 2005 at 11:48:49PM +0000, Christian Weisgerber wrote:
> 
> I don't think there is a reliable solution without something like
> FreeBSD's -v or GNU's -d extensions.
> 

If you only want yesterday then this should do (it is ugly but it has
been tested on Solaris/Linux/NetBSD):

#!/bin/sh
#
# A way of working out what the date was yesterday - portably.
#

isleapyear()
{
#
# Determining leap years is easy (sortof).
# returns 0(true) if leapyear, 1 otherwise
#

    if [ `expr $1 % 4` -eq 0 ]
    then
        if [ `expr $1 % 100` -eq 0 ]
        then
            if [ `expr $1 % 400` -eq 0 ]
            then
                return 0
            fi
        else
            return 0
        fi
    fi
    return 1
}

#
# Return the last day of the month taking into account leap years, $1 
# is the month
#
ldom() {

    case $1 in
        1|3|5|7|8|10|12)
            day=31
            ;;

        2)
            if isleapyear $year
            then
                day=29
            else
                day=28
            fi
            ;;

        *)
            day=30
            ;;
    esac

    return $day
}

#
# Calculate the date for yesterday.  Takes three parameters, $1 is the day
# $2 is the month and $3 is the year
#
yesterday() {

    day=$1
    month=$2
    year=$3

    if [ $day -ne 1 ]
    then
        day=`expr $day - 1`
    else
        if [ $month -ne 1 ]
        then
            month=`expr $month - 1`
            ldom $month
        else
            year=`expr $year - 1`
            month=12
            day=31
        fi
    fi
}

#
# This is just for testing...
#
while read day month year
do
    yesterday $day $month $year
    echo "Yesterday was $day/$month/$year"
done

-- 
Brett Lymn

Reply via email to