linux 计算字符串日期,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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值