给定 YYYY-MM-DD,如何查找周的开始日期和一周的结束日期?



有没有一种方法可以在linux中使用日期函数来获得一周开始的确切日期&给定YYYY-MM-DD的周末?

例如,我可以输入2020-07-24,它将返回2020-07-20(星期一(&CCD_ 3(星期日(作为开始&分别为本周的结束日期。

这个shell脚本应该适用于大多数Linux,因为它们大多使用GNU日期

它将输入转换为epoch秒,然后返回一天,直到星期一找到

#!/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"

最新更新