Linux下如何用date获取当前日期的前一天

今天遇到这个问题,从网上找到这两个合适的解答。

方法一:date命令的显示是与环境变量TZ有关的


$#看当前时区
$echo $TZ
CST-8
$#显示当前时间
$date
Mon Apr  2 15:48:36 CST 2002
$#改变当前时区,
TZ=CST+16;export TZ
$#显示当前时间(中间未改变系统时间,但date命令的显示已为昨天)
Mon Apr  1 15:48:33 CST 2002

=========================
方法二:一个详细的SCRIPT


#!/bin/sh

# ydate: A Bourne shell script that
# prints yestarday's date
# Output Form: Month Day Year
# From Focus on Unix: http://unix.about.com

# Set the current month day and year.
month=`date +%m`
day=`date +%d`
year=`date +%Y`

# 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
  
  # Find the preivous month.
  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

# Print the month day and year.
echo $month $day $year
exit 0

============
如果是简单的只是想获得昨天的日期就很简单了,只要今天不是一号,呵呵
month=`date +%m`
day=`date +%d`
year=`date +%Y`
day=`expr $day - 1`

export DATEYMD=$year$month$day
echo $DATEYMD
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值