【问题标题】:How to make date command work in relation to custom specified date?如何使日期命令与自定义指定日期相关?
【发布时间】:2013-09-25 18:59:36
【问题描述】:

在 Linux 中有一个非常棒的命令 date 可以这样使用:

# Get some cool date in relation to systems date:
date  -d "last Sunday -7 days"
Sun Sep 15 00:00:00 PDT 2013

# Set systems date:
date --set="2013-03-04"
Mon Mar  4 00:00:00 PST 2013

基本上我希望能够像这样运行这个命令:

date --date="last Sunday -7 days" +%Y-%m-%d
2013-09-15

但不是与今天的系统日期有关,而是与另一个以字符串形式(例如“2013-09-01”)或其他形式的计算生成的某个日期有关。

请帮我弄清楚该怎么做。

【问题讨论】:

    标签: linux bash date environment-variables zsh


    【解决方案1】:

    使用函数:

    function get_last_day {
        local date=$1 day=$2 format=$3 a b i
        for (( i = 0; i <= 6; ++i )); do
            read -r a b < <(exec date -d "$date - $i days" "+%a $format")
            if [[ $a == "$day" ]]; then
                echo "$b"
                return
            fi
        done
    }
    
    get_last_day '2013-09-18' Sun '%Y-%m-%d'
    

    输出:

    2013-09-15
    

    【讨论】:

    • 谢谢,但有什么办法可以让它工作: date -d '2013-09-18 last Sunday' +%Y-%m-%d 这将返回 2013-09-15
    • 嗯,谢谢,我一直在寻找一些优雅的方法,但看起来我还是要写一个 python 脚本。
    猜你喜欢
    • 1970-01-01
    • 2014-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-07
    • 1970-01-01
    相关资源
    最近更新 更多