45fan.com - 路饭网

搜索: 您的位置主页 > 网络频道 > 阅读资讯:如何在linux下用脚本获得前一天的日期?

如何在linux下用脚本获得前一天的日期?

2016-09-02 15:30:44 来源:www.45fan.com 【

如何在linux下用脚本获得前一天的日期?

修改时区法:

用date获得前一天的日期

$#看当前时区

$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

不过这样改完后,该用户下的c程序中,time返回的日期也变成前一天了。

下面是个原始方法但好用:

/////////////////////////////////////////////////////////////////

#!/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

///////////////////////////////////////////////////////

如果你的主机能够连接到数据库的话,比如可以连接到SYBASE数据库,那就可以利用数据库里面计算时间的丰富的函数了,比如

dateadd(day,getdate(),-1)

就能得到最天的日期了

 

本文地址:http://www.45fan.com/a/question/71353.html
Tags: linux 脚本 获得
编辑:路饭网
关于我们 | 联系我们 | 友情链接 | 网站地图 | Sitemap | App | 返回顶部