2

Linux date 命令获取某日期的前一天

 3 years ago
source link: https://blogread.cn/it/article/312?f=hot1
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Linux date 命令获取某日期的前一天

浏览:7903次  出处信息

    最近需要写个 shell script,给定一个日期参数,它要得到该日期的前一天,然后做剩下的事。执行的时候就是这样:

<table style="BORDER-RIGHT: #cccccc 1px dotted; TABLE-LAYOUT: fixed; BORDER-TOP: #cccccc 1px dotted; BORDER-LEFT: #cccccc 1px dotted; BORDER-BOTTOM: #cccccc 1px dotted" cellspacing="0" cellpadding="6" width="95%" align="center" border="0"><tbody><tr><td style="WORD-WRAP: break-word" bgcolor="#fdfddf"><font style="FONT-WEIGHT: bold; COLOR: #990000">以下是代码片段:</font><br># ./foo.sh 2009-03-01</td></tr></tbody></table>

    初看,这个问题有些棘手。最原始的办法是写个比较繁琐的函数,知道每个月分别是多少天,还要处理一下闰年的情况――这也有点太繁琐了,呵呵。

    稍微看一下 date 命令,就发现利用它可以很方便的写出一个非常 stable 的函数。date 可以通过 -d 指定一个日期,然后用指定的格式输出。-d 不仅可以接受 “2009-03-01″ 或者 yesterday 这样的格式,还可以接受一个从 1970 年开始至今的秒数,当然也可以指定日期输出这样的秒数。如:

<table style="BORDER-RIGHT: #cccccc 1px dotted; TABLE-LAYOUT: fixed; BORDER-TOP: #cccccc 1px dotted; BORDER-LEFT: #cccccc 1px dotted; BORDER-BOTTOM: #cccccc 1px dotted" cellspacing="0" cellpadding="6" width="95%" align="center" border="0"><tbody><tr><td style="WORD-WRAP: break-word" bgcolor="#fdfddf"><font style="FONT-WEIGHT: bold; COLOR: #990000">以下是代码片段:</font><br># date +%s <br>1252591191 <br># date -d @1252591191 +%F <br>2009-09-10</td></tr></tbody></table>

    这样,事情就变得很简单了。先用 date 命令将该日期转换成秒数,减去一天的秒数 86400,然后再转化成正常易读的日期格式,就可以了,不需要考虑复杂的大小月以及闰年问题。以下是简单的例子:

<table style="BORDER-RIGHT: #cccccc 1px dotted; TABLE-LAYOUT: fixed; BORDER-TOP: #cccccc 1px dotted; BORDER-LEFT: #cccccc 1px dotted; BORDER-BOTTOM: #cccccc 1px dotted" cellspacing="0" cellpadding="6" width="95%" align="center" border="0"><tbody><tr><td style="WORD-WRAP: break-word" bgcolor="#fdfddf"><p><font style="FONT-WEIGHT: bold; COLOR: #990000">以下是代码片段:</font><br>#!/bin/sh  <br>function get_day_before {  <br>seconds=`date -d $1 +%s`  <br>seconds_yesterday=$((seconds - 86400))  <br>day_before=`date -d @$seconds_yesterday +%F`  <br>echo $day_before <br>}  </p><p>get_day_before $1</p></td></tr></tbody></table>

    最后,必须支持一下这个 World Calendar。它非常有规律,非常容易记忆,季度、月份、星期完美地吻合在一起。

觉得文章有用?立即:

和朋友一起 共学习 共进步!

建议继续学习:

QQ技术交流群:445447336,欢迎加入!
扫一扫订阅我的微信号:IT技术博客大学习

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK