gpt4 book ai didi

linux - 在 Linux 中获取给定日期的前一个工作日的函数

转载 作者:可可西里 更新时间:2023-11-01 11:51:22 26 4
gpt4 key购买 nike

给定一个输入日期,我想编写一个 bash 函数来输出前一个工作日。我指的是前的一天(周一到周五);我不需要它来考虑假期。因此,例如,给定“2018 年 1 月 2 日”,结果应为“2018 年 1 月 1 日”(即使那是假期),但给定“2018 年 1 月 1 日”,结果应为“2017 年 12 月 29 日”(因为 12 月 30 日和 31 日是周六和周日)。我不需要任何特定的格式;只是人类可读且 date -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

关于linux - 在 Linux 中获取给定日期的前一个工作日的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53550572/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com