日期:如果在命令中添加 "UTC",则错过或不正确的小时数

date: hours missed or incorrect if add "UTC" in the commands

您好,我想在我的 bash 脚本中使用 date 来更新计算时间步骤。假设我有 YMDH=2017032522(在 UTC 时区)并且我想在 12 小时后获取时间戳(应该是 2017032610,也在 UTC 时区)。我尝试了以下命令:

INC=+12hours
date +%Y%m%d -d "${YMDH::8} ${YMDH:8:2}:00:00 UTC ${INC}"

然后我得到的结果是 20170326。很明显,这里没有显示小时数。但是如果我尝试使用

INC=+12hours
date +%Y%m%d -d "20170325 22:00:00 UTC ${INC}"

我可以得到 2017032612 的结果。时间在这里显示,但它是错误的...我希望在这里得到 2017032610

我知道我可以在这里使用 --debug 选项。所以我尝试使用 date +%Y%m%d --debug -d "${YMDH::8} ${YMDH:8:2}:00:00 UTC ${INC}",这里是日志信息:

(base) $ date +%Y%m%d --debug -d "${YMDH::8} ${YMDH:8:2}:00:00 UTC ${INC}"
date: parsed number part: (Y-M-D) 2017-03-25
date: parsed time part: 22:00:00
date: parsed relative part: +12 hour(s)
date: parsed zone part: UTC+00
date: input timezone: parsed date/time string (+00)
date: using specified time as starting value: '22:00:00'
date: starting date/time: '(Y-M-D) 2017-03-25 22:00:00 TZ=+00'
date: '(Y-M-D) 2017-03-25 22:00:00 TZ=+00' = 1490479200 epoch-seconds
date: after time adjustment (+12 hours, +0 minutes, +0 seconds, +0 ns),
date:     new time = 1490522400 epoch-seconds
date: warning: daylight saving time changed after time adjustment
date: timezone: system default
date: final: 1490522400.000000000 (epoch-seconds)
date: final: (Y-M-D) 2017-03-26 10:00:00 (UTC)
date: final: (Y-M-D) 2017-03-26 12:00:00 (UTC+02)
20170326

所以有没有人可以帮助我?谢谢!

首先:将所有内容转换为纪元以来的秒数。

然后,加秒。

然后,在使用时转换回您需要的格式

sec=$(date -ud "2017-03-25 22:00:00" +%s)
# I want to get the timing stamps after 12 hours
sec=$((sec + 12 * 60 *60))
# which should be 2017032610
date -ud "@$sec" +%Y%m%d%H