linux下字符串转换成日期

#!/bin/bash
thedate=$1
if ! test $thedate
then
    thedate=$(/bin/date  -d-1day "+%Y%m%d")
fi

#####定义一个函数,输入参数1是日期字符串,比如20110211 ,输入参数2是要增加的日期,比如2
#####如果toDate 20110211 1就是要计算2011年2月11日的后一天是多少
#####如果toDate 20110211 -1就是要计算2011年2月11日的前一天是多少
toDate()
{
   startdate=$1;
   days=$2;
   timestamp_startdate=`date -d ${startdate} +%s`
   timestamp_resultdate=`expr ${timestamp_startdate} '+' ${days} '*' 86400`
   resultdate=`date -d @${timestamp_resultdate} +%Y%m%d`
}

###如果给定的日期是周五,那么将最近7天列出来
ifweek=`date -d ${thedate} +%u`
if [ ${ifweek} -eq "5" ]; then
  thedates=$thedate

   for i in {-1..-6}
   do
      toDate $thedate $i;
      thedates=$thedates" "${resultdate};
   done
   echo "$thedates"
fi

#############判断输入的字符串是否是这个月的最后一天,如果是则打印 yyyymmdd is the last day of month yyyymm ##################
ifLastDayOfMonth=`date -d ${thedate} +%s`
ifLastDayOfMonth=`expr ${ifLastDayOfMonth} '+' 86400`
ifLastDayOfMonth=`date -d @${ifLastDayOfMonth} +%Y%m`
if [ ${thedate:0:6} -ne $ifLastDayOfMonth ]; then
   echo "$thedate is the last day of month ${thedate:0:6}"
fi

 

#######将上述内容存成文件mydate.sh, chmod 755 mydates.sh ,运行./mydates.sh 20110211 则输出:20110211 20110210 20110209 20110208 20110207 20110206 20110205,运行./mydates.sh 20110228 则输出:20110228 is the last day of month 201102

你可能感兴趣的:(linux,Date)