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

时间:2020-07-28 04:46:52

标签: linux bash date scripting

有没有一种方法可以在Linux中使用date函数来获取给定YYYY-MM-DD的星期几和星期几的确切日期?

例如,我可以输入2020-07-24,它将分别返回2020-07-20(星期一)和2020-07-26(星期日)作为该特定星期的开始和结束日期。

1 个答案:

答案 0 :(得分:0)

此shell脚本应该在大多数Linux上都可以使用,因为它们大多使用GNU日期

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

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