尝试过这个但失败了
now=$(date +%Y%m%d%H%M%S)
past=$(date +%Y%m%d%H%M%S -d "${now} -5minutes")
echo $past
结果:
date: invalid date ‘20200120175610 -5minutes’
TT
答案1
这对我有用,使用date (GNU coreutils) 8.26
.
$ date -d "5 minutes ago" +%Y%m%d%H%M%S
20200120101533
答案2
看来 GNU date 无法解析该格式的时间戳。领先部分为一年:
% date +%Y%m%d%H%M%S -d 20200120175610 --debug
date: parsed number part: (Y-M-D) 2020012017-56-10
date: input timezone: system default
date: warning: using midnight as starting time: 00:00:00
date: error: invalid date/time value:
date: user provided time: '(Y-M-D) 2020012017-56-10 00:00:00'
date: normalized time: '(Y-M-D) 2020012021-08-10 00:00:00'
date: ---- --
date: possible reasons:
date: numeric values overflow;
date: missing timezone
date: invalid date ‘20200120175610’
如果它没有出错,那么它可能没有溢出,但它仍然没有达到您的预期:
% date +%Y%m%d%H%M%S -d "20200120181002 -5minutes" --debug
date: parsed hybrid part: -5 minutes
date: input timezone: system default
date: warning: using midnight as starting time: 00:00:00
date: starting date/time: '(Y-M-D) 2020012018-10-02 00:00:00'
date: '(Y-M-D) 2020012018-10-02 00:00:00' = 63745360147926000 epoch-seconds
date: after time adjustment (+0 hours, -5 minutes, +0 seconds, +0 ns),
date: new time = 63745360147925700 epoch-seconds
date: timezone: system default
date: final: 63745360147925700.000000000 (epoch-seconds)
date: final: (Y-M-D) 2020012018-10-01 14:55:00 (UTC)
date: final: (Y-M-D) 2020012018-10-01 23:55:00 (UTC+09)
20200120181001235500
使用不同的时间戳格式。我建议使用 ISO-8601,并在输出时根据需要重新格式化:
% now=$(date --iso-8601=seconds)
% past=$(date -d "$now - 5 minutes" --iso-8601=seconds)
% printf "%s\n" "$now" "$past"
2020-01-20T18:29:50+09:00
2020-01-20T18:24:50+09:00
% date -d "$past" +%Y%m%d%H%M%S
20200120182450
答案3
它可能会像这样工作。
past=$(date +%Y%m%d%H%M%S -d ${now} -d "-5minutes")