【问题标题】:Given YYYY-MM-DD, how to find start date of week & end date of week? [duplicate]给定 YYYY-MM-DD,如何找到一周的开始日期和一周的结束日期? [复制]
【发布时间】:2020-11-17 11:38:02
【问题描述】:
有没有办法在 linux 中使用 date 函数来获取给定 YYYY-MM-DD 的一周开始和一周结束的确切日期?
例如,我可以输入2020-07-24,它会分别返回2020-07-20(星期一)和2020-07-26(星期日)作为这一周的开始和结束日期。
【问题讨论】:
-
是的,但不是直接的。你试过什么吗?一个好的起点是阅读date manual 并查看它有哪些选项。特别是它可以用+%u 告诉你星期几,然后你可以做一些计算并使用--date='X days ago'(作为例子)。
-
标签:
linux
bash
date
scripting
【解决方案1】:
这个 shell 脚本应该可以在大多数 Linux 上运行,因为它们大多使用 GNU date
它将输入转换为纪元秒,然后返回一天直到星期一
找到了
#!/bin/bash
# take the parameter from command line
d="$1"
# find the current time as seconds since 1st Jan 1970 (epoch time)
start=$(date -d "$d" '+%s')
consider="$start"
# day of the week for the time we are considering
dow=$(date -d "@$consider" '+%A')
# is the day of the week monday? if not, carry on
while [[ "$dow" != "Monday" ]]; do
# adjust the time to be a day further in the past, 24*60*60 seconds is 1 day
let "consider=$consider - 86400"
dow=$(date -d "@$consider" '+%A')
done
# output the found date
date -d "@$consider"