Thursday, January 20, 2011

Get Date of Yesterday

----------------------------Ksh Shell Script--------------------------------

#! /usr/bin/ksh
# Get yesterday's date in YYYY-MM-DD format.
# With argument N in range 1..28 gets date N days before.
# Tapani Tarvainen January 2002
# This code is in the public domain.

OFFSET=${1:-1}

case $OFFSET in
  *[!0-9]* | ???* | 3? | 29) print -u2 "Invalid input" ; exit 1;;
esac

eval `date "+day=%d; month=%m; year=%Y`
typeset -Z2 day month
typeset -Z4 year

# Subtract offset from day, if it goes below one use 'cal'
# to determine the number of days in the previous month.
day=$((day - OFFSET))
if (( day <= 0 )) ;then
  month=$((month - 1))
  if (( month == 0 )) ;then
    year=$((year - 1))
    month=12
  fi
  set -A days `cal $month $year`
  xday=${days[$(( ${#days[*]}-1 ))]}
  day=$((xday + day))
fi

print $year-$month-$day
print $month/$day/${year#??}


------------------------Bash Shell Script------------------------------

#!/bin/bash

OFFSET=1;

eval `date "+day=%d; month=%m; year=%Y"`

# Subtract offset from day, if it goes below one use 'cal'

# to determine the number of days in the previous month.

day=`expr $day - $OFFSET`

if [ $day -le 0 ] ;then

month=`expr $month - 1`

if [ $month -eq 0 ] ;then

year=`expr $year - 1`

month=12

fi

set `cal $month $year`

xday=${$#}

day=`expr $xday + $day`

fi

echo $year-$month-$day


------------------------- Linux--------------------------

curdate=`date +%y%m%d -d "yesterday"`

No comments:

Post a Comment