linux取工作日,在Linux中获取给定日期的前一个工作日的功能

给定输入日期,我想编写一个bash函数,该函数将输出前一个工作日.

我的意思是前一个工作日(星期一至星期五);

我不需要考虑假期.

因此,例如,给定“ 2018年1月2日”,结果应为“ 2018年1月1日”

(即使那是个假期),

但给定的是“ 2018年1月1日”,则结果应为“ 2017年12月29日”

(因为12月30日和31日分别是星期六和星期日).

我不需要任何特殊格式;

只是迄今为止人类可以理解并且可以接受的东西-d.

我已经尝试了以下方法,但是似乎没有正确考虑输入日期:

function get_previous_busday()

{

DAY_OF_WEEK=`$1 +%w`

if [ $DAY_OF_WEEK -eq 0 ] ; then

LOOKBACK=-2

elif [ $DAY_OF_WEEK -eq 1 ] ; then

LOOKBACK=-3

else

LOOKBACK=-1

fi

PREVDATE=date -d "$1 $LOOKBACK day"

}

我想今天将其应用:

PREVDATE=$(get_previous_busday $(date))

echo $PREVDATE

而昨天:

PREVDATE=$(get_previous_busday (date -d "$(date) -1 day"))

echo $PREVDATE

但它不起作用:

main.sh: line 3: Fri: command not found

main.sh: line 4: [: -eq: unary operator expected

main.sh: line 6: [: -eq: unary operator expected

main.sh: line 11: -d: command not found

main.sh: command substitution: line 20: syntax error near unexpected token `date'

main.sh: command substitution: line 20: `get_previous_busday (date -d "$(date) -1 day"))'

解决方法:

一个您想要做的功能是:

get_previous_busday() {

if [ "$1" = "" ]

then

printf 'Usage: get_previous_busday (base_date)\n' >&2

return 1

fi

base_date="$1"

if ! day_of_week="$(date -d "$base_date" +%u)"

then

printf 'Apparently "%s" was not a valid date.\n' "$base_date" >&2

return 2

fi

case "$day_of_week" in

(0|7) # Sunday should be 7, but apparently some people

# expect it to be 0.

offset=-2 # Subtract 2 from Sunday to get Friday.

;;

(1) offset=-3 # Subtract 3 from Monday to get Friday.

;;

(*) offset=-1 # For all other days, just go back one day.

esac

if ! prev_date="$(date -d "$base_date $offset day")"

then

printf 'Error calculating $(date -d "%s").\n' "$base_date $offset day"

return 3

fi

printf '%s\n' "$prev_date"

}

例如,

$get_previous_busday

Usage: get_previous_date (base_date)

$get_previous_busday foo

date: invalid date ‘foo’

Apparently "foo" was not a valid date.

$get_previous_busday today

Fri, Nov 30, 2018 1:52:15 AM

$get_previous_busday "$(date)"

Fri, Nov 30, 2018 1:52:51 AM

$PREVDATE=$(get_previous_busday $(date))

$echo "$PREVDATE"

Fri, Nov 30, 2018 12:00:00 AM

$get_previous_busday "$PREVDATE"

Thu, Nov 29, 2018 12:00:00 AM

$PREVPREVDATE=$(get_previous_busday "$PREVDATE")

$printf '%s\n' "$PREVPREVDATE"

Thu, Nov 29, 2018 12:00:00 AM

$get_previous_busday "$PREVPREVDATE"

Wed, Nov 28, 2018 12:00:00 AM

标签:bash,linux,date,function

来源: https://codeday.me/bug/20191024/1924051.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值