`

写一个Bash脚本来计算母亲节和父亲节的日期(推荐)

 
阅读更多

写一个Bash脚本来计算母亲节和父亲节的日期

母亲节(每年5月的第二个星期日

  2005年5月8日

  2006年5月14日

  2007年5月13日

  2008年5月11日

  2009年5月10日

  2010年5月9日

  2011年5月8日

  2012年5月13日

父亲节(6月第三个星期日),下面是最近几年的父亲节日期

  2005年6月19日
  2006年6月18日
  2007年6月17日
  2008年6月15日
  2009年6月21日
  2010年6月20日
  2011年6月19日

  2012年6月17日

 

下面是Linux查看某年某月的日历的方式。
[root@node56 ~]# cal 5 2012
     五月 2012      
日 一 二 三 四 五 六
       1  2  3  4  5
 6  7  8  9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31

下面的脚本用来计算指定年份的母亲节和父亲节的日期。

Bash脚本:calc_date.sh

#!/bin/sh

# 母亲节(每年5月的第二个星期日 )
# usage: mother_day [year]
mother_day()
{
        local may1  # 5月1日
        if [ "$1" ]; then
                may1=$1-05-01   # 也可以是是$1/05/01
        else
                may1=5/1   # 也可以是05/01,但不能是05-01
        fi
        #date -d $may1
        # 看5月1日是星期几
        local w=$(date +%w -d $may1)    # %w 0=星期天 1-6=星期一到六
        #echo $w
        if [ $w -eq 0 ]; then   # 如果是5月1日星期天,就跳过一个星期
                date +%F -d "$may1 +1 week"
        else    # 如果5月1日不是星期天,就跳过两个星期,再减去w天
                date +%F -d "$may1 +2 week -$w day"
        fi
}

# 父亲节(每年6月的第三个星期日)
# usage: father_day [year]
father_day()
{
        local june1     # 保存6月1日的日期
        if [ "$1" ]; then
                june1=$1-06-01
        else
                june1=6/1
        fi
        # 因为采用1-7表示星期几,简化了计算逻辑
        local w=$(date +%u -d $june1)   # %u 7=星期天,1-6=星期一到六
        date +%F -d "$june1 +3 week -$w day"
}

# usage: ./calc_date.sh [year]
if [ "$1" ]; then
        echo Mother Day of year $1 is $(mother_day "$1")
        echo Father Day of year $1 is $(father_day "$1")
else
        echo Mother Day of this year is $(mother_day)
        echo Father Day of this year is $(father_day)
fi
  

 

[root@node56 ~]# ./calc_date.sh
Mother Day of this year is 2011-05-08
Father Day of this year is 2011-06-19
[root@node56 ~]# ./calc_date.sh 2011
Mother Day of year 2011 is 2011-05-08
Father Day of year 2011 is 2011-06-19
[root@node56 ~]# ./calc_date.sh 2010
Mother Day of year 2010 is 2010-05-09
Father Day of year 2010 is 2010-06-20
[root@node56 ~]# ./calc_date.sh 2009
Mother Day of year 2009 is 2009-05-10
Father Day of year 2009 is 2009-06-21
[root@node56 ~]# ./calc_date.sh 2008
Mother Day of year 2008 is 2008-05-11
Father Day of year 2008 is 2008-06-15
[root@node56 ~]# ./calc_date.sh 2007
Mother Day of year 2007 is 2007-05-13
Father Day of year 2007 is 2007-06-17
[root@node56 ~]# ./calc_date.sh 2006
Mother Day of year 2006 is 2006-05-14
Father Day of year 2006 is 2006-06-18
[root@node56 ~]# ./calc_date.sh 2005
Mother Day of year 2005 is 2005-05-08
Father Day of year 2005 is 2005-06-19
[root@node56 ~]# ./calc_date.sh 2012
Mother Day of year 2012 is 2012-05-13
Father Day of year 2012 is 2012-06-17

3
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics