Here is a small shell script to do date addition and subtraction. This works on the bash shell with GNU Date.
#!/bin/bash
function getPreviousDateTime(){
d1=`date -d "$1" +'%Y-%m-%d %H:%M:%S'`;
secs1=`date -d"$d1" +%s`;
secs2=`expr $secs1 - $2`;
# change to %H:%M:%S if you want the nos. left padded
result=`date -d@"$secs2" +'%Y-%m-%d %-H:%-M:%-S'`;
# return formatted string
echo $result;
}
function getNextDateTime(){
d1=`date -d "$1" +'%Y-%m-%d %H:%M:%S'`;
secs1=`date -d"$d1" +%s`;
secs2=`expr $secs1 + $2`;
result=`date -d@"$secs2" +'%Y-%m-%d %H:%M:%S'`;
# return formatted string
echo $result;
}
# Tests
echo `getPreviousDateTime "2012-04-29 18:00:31" 30`
echo `getPreviousDateTime "2012-04-29 00:00:00" 60`
echo `getPreviousDateTime "2012-04-29 02:00:00" 60`
echo `getNextDateTime "2012-04-29 19:00:00" 60`;
echo `getNextDateTime "2012-04-30 23:59:00" 60`;
echo `getNextDateTime "2012-02-28 23:59:00" 60`;
echo `getNextDateTime "2012-02-28 2:59:00" 60`;
#!/bin/bash
function getPreviousDateTime(){
d1=`date -d "$1" +'%Y-%m-%d %H:%M:%S'`;
secs1=`date -d"$d1" +%s`;
secs2=`expr $secs1 - $2`;
# change to %H:%M:%S if you want the nos. left padded
result=`date -d@"$secs2" +'%Y-%m-%d %-H:%-M:%-S'`;
# return formatted string
echo $result;
}
function getNextDateTime(){
d1=`date -d "$1" +'%Y-%m-%d %H:%M:%S'`;
secs1=`date -d"$d1" +%s`;
secs2=`expr $secs1 + $2`;
result=`date -d@"$secs2" +'%Y-%m-%d %H:%M:%S'`;
# return formatted string
echo $result;
}
# Tests
echo `getPreviousDateTime "2012-04-29 18:00:31" 30`
echo `getPreviousDateTime "2012-04-29 00:00:00" 60`
echo `getPreviousDateTime "2012-04-29 02:00:00" 60`
echo `getNextDateTime "2012-04-29 19:00:00" 60`;
echo `getNextDateTime "2012-04-30 23:59:00" 60`;
echo `getNextDateTime "2012-02-28 23:59:00" 60`;
echo `getNextDateTime "2012-02-28 2:59:00" 60`;