Gnu 日期输入格式

Gnu 日期输入格式

我正在尝试理解

date -d "something"

具体来说,我想了解“星期几项目”的用法。日期手册页将您引至以下一组 GNU 页面以获取有关此主题的信息:gnu.org - 日期输入格式

这涵盖了 GNU 日期输入格式的整个主题。具体来说,它对“星期几”进行了如下说明:

28.6 星期几项目

明确提到星期几将会转发日期(仅在必要时)以便将来到达星期几。

星期几可以完整拼写出来:“Sunday”、“Monday”、“Tuesday”、“Wednesday”、“Thursday”、“Friday”或“Saturday”。星期几可以缩写为前三个字母,后面可以加句号。也可以使用特殊缩写,例如“Tues”表示“Tuesday”,“Wednesday”表示“Wednesday”,“Thur”或“Thurs”表示“Thursday”。

可以在星期几项前面加上数字,以向前移动补充的星期数。最好用“第三个星期一”这样的表达方式。在这种情况下,“最后一天”或“第二天”也是可以接受的;它们会在该天本身所代表的日期之前或之后移动一周。

星期几项后面的逗号将被忽略。

根据这些信息,我希望以下命令告诉我 2016 年第三个星期四的日期。

jonathan@Aristotle:~$ date -d "4/1 3 thursday" +"%y %m %d"
16 04 01

如您所见,星期几规范被接受但被忽略,结果是 4 月 1 日,而不是第三个星期四。文档指出,“星期几”规范应添加到基准日期规范中如果有必要。不幸的是,背后的规则如果有必要没有给出。有人知道如何使用 date 命令来实现这一点吗?我显然可以使用 Bash 脚本来解决这个问题。

答案1

仅供参考,星期几的风格如下dateutils

$ dateconv 2016-04-03-04 -f %F
2016-04-21

根据要求,日期是 2016 年 4 月的第三个星期四。

或者,可以明确指定输入:

$ dateconv -i "%m/1 %c %A" "4/1 3 thursday"
2017-04-03-04

(我不确定你例子中的 /1 是什么)。

免责声明:我是该软件包的作者。

答案2

我发现了一种不依赖于输入的神秘语法的方法:

date -d

该函数解决了这个问题:

function calculateTargetDay {
# Calculates the day in the month of the nth. weekday in month
# $1 is the current date stored in an array as yy mm dd integers
# $2 is the day of the week as an integer, Monday = 1
# $3 is the week of the month as an integer - first week = 1
# Returns the day of month in the $daymonth variable which should be defined in the main-line

daymonth=$(( $(date -d "${1[0]}-${1[1]}-1" +%u) - 1 )) # Get relative day in week of 1st. of month
# Calculate release day within month
daymonth=$(( $daymonth - $2 + 7 + (( $3 - 1) * 7 ) ))}  # Gives day in month of nth weekday in month

这以紧凑的方式封装了计算。

相关内容