IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    shell 表示昨天 明天

    rock发表于 2013-04-25 11:29:12
    love 0

    转自: http://hi.baidu.com/oracledba/item/e8c5e02e96ce09150975083a

    #!/bin/bash
    current=`date +%s` //得到时间戳


    ONE_DAY_SECOND=$((24*3600))//一天所经过的秒数


    current=$(($current - $ONE_DAY_SECOND))//当前的时间戳减去一天的秒数,得到一天前的时间戳


    yesterday=`date +%Y-%m-%d -d "1970-01-01 UTC $current seconds"`//通过-d格式化时间戳为时间,同时使用+%Y-%m-%d去格式化日期为我们需要的格式,显示格式就是YYYY-MM-DD,如果想显示为YYYYMMDD,那么就用+%Y%m%d这种方法去格式化


    还有更简便的方便。。就是下面。。

    yesterday=`date +%Y%m%d -d "1 day ago"`

    ----------------------------------------------------------------------------------

    表示昨天日期

    date -d 'yesterday' +%Y%m%d

    格式如:20091208

    在shell中表示昨天、明天的命令很方便,並且格式也可以隨意定义。

    # date --date=‘yesterday’昨天的日期

    # date --date=‘tomorrow’ 明天的日期

    # date -d ‘-n day’表示n天前的日期

    # date -d ‘+n day’表示n天后的日期

    昨天的命令是:

    yesterdayformat=`date --date='yesterday' "+%Y-%m-%d_%H:%M:%S"`

    echo $yesterdayformat

    輸出格式是:

    2009-01-18_11:34:04

    明天的命令是:

    tomorrowformat=`date --date='tomorrow' "+%Y-%m-%d_%H:%M:%S"`

    echo $tomorrowformat

    輸出格式是:

    2009-01-20_11:35:19

    以前我写的輸入昨天日期的脚本是:

    #!/bin/sh

    month="`date "+%m"`"

    day="`date "+%d"`"

    year="`date "+%Y"`"

    ##########**********Export Yesterday Format To Sign File**********###########

    ##Add 0 to month. This is a trick to make month an unpadded integer.

    month="`expr $month + 0`"

    ##Subtract one from the current day.

    day="`expr $day - 1`"

    ##If the day is 0 then determine the last day of the previous month.

    if [ "$day" -eq 0 ]

    then

    month="`expr $month - 1`"

    ##If the month is 0 then it is Dec 31 of the previous year.

    if [ "$month" -eq 0 ]

    then

    month=12

    day=31

    year="`expr $year - 1`"

    ##If the month is not zero,we need to find the last day of the month.

    else

    case $month in

    1|3|5|7|8|10|12) day=31

    ;;

    4|6|9|11) day=30

    ;;

    2)

    if [ `expr "$year" % 4` -eq 0 ]

    then

    if [ `expr "$year" % 400` -eq 0 ]

    then

    day=29

    elif [ `expr "$year" % 100` -eq 0 ]

    then

    day=28

    else

    day=29

    fi

    else

    day=28

    fi

    ;;

    esac

    fi

    fi

    ##Define date format

    if [ "$day" -gt 0 -a "$day" -lt 10 ]

    then

    day=0${day}

    fi

    ##Define month format

    if [ "$month" -gt 0 -a "$month" -lt 10 ]

    then

    month=0${month}

    fi

    YESTDATEFULL="`echo "$year-$month-$day"`"

    echo $YESTDATEFULL



沪ICP备19023445号-2号
友情链接