使用 bash 在 YYYYMMDDHHMMSS 中增加日期的小时/分钟/秒
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38491986/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Increment hours/minutes/seconds of date in YYYYMMDDHHMMSS using bash
提问by jojo
Suppose todays' date is formatted to YYYYMMDDHHMMSS such as 20160720152654. I would want to add hours or minutes or seconds to date.
假设今天的日期格式为 YYYYMMDDHHMMSS,例如 20160720152654。我想添加小时或分钟或秒到日期。
Add 1 hour should change date to 20160720162654 Add 1 minute should change date to 20160720152754 Add 1 second should change date to 20160720152655
添加 1 小时应将日期更改为 20160720162654 添加 1 分钟应将日期更改为 20160720152754 添加 1 秒应将日期更改为 20160720152655
This seems to give me incorrect results
这似乎给了我不正确的结果
d=date +%Y%m%d%H%M%S
pd=$(($d + ($d % (15 * 60))))
echo $d
echo $pd
d= date +%Y%m%d%H%M%S
pd=$(($d + ($d % (15 * 60)))) echo $d echo $pd
Output 20160720155141 20160720155482
产量 20160720155141 20160720155482
回答by anubhava
You can manipulate input to pass it to date -d
:
您可以操纵输入将其传递给date -d
:
s='20160720162654'
# add 1 minute
date -d "${s:0:8} ${s:8:2}:${s:10:2}:${s:12:2} +1 min" '+%Y%m%d%H%M%S'
20160720112754
# add 1 sec
date -d "${s:0:8} ${s:8:2}:${s:10:2}:${s:12:2} +1 sec" '+%Y%m%d%H%M%S'
20160720112655
# add 1 hour
date -d "${s:0:8} ${s:8:2}:${s:10:2}:${s:12:2} +1 hour" '+%Y%m%d%H%M%S'
20160720122654
回答by murtiko
Minor addition to anubhava's answer:
anubhava 的回答的小补充:
Since the timezone info is not available in YYYYMMDDHHMMSS, you may get unexpected results depending on your actual timezone, such as:
由于时区信息在 YYYYMMDDHHMMSS 中不可用,根据您的实际时区,您可能会得到意想不到的结果,例如:
s=20190201140000
date -d "${s:0:8} ${s:8:2}:${s:10:2}:${s:12:2} +1 minute" '+%Y%m%d%H%M%S'
20190201160100
# !? was expecting 20190201140100
As far as I could understand, this happens because of the +1 minute
expression, which causes date
to ignore your current timezone:
据我所知,这是因为+1 minute
表达式导致date
忽略您当前的时区:
date
Thu Feb 7 17:07:28 +03 2019
date -d "20190207 17:07" "+%Y%m%d%H%M%S"
20190207170700
date -d "20190207 17:07 + 1 minute" "+%Y%m%d%H%M%S"
20190207190800
In my case, the timezone offset was +3, so that was causing problems:
就我而言,时区偏移量是 +3,因此会导致问题:
date +%Z
+03
You should be able to make it work on all timezones, by adding the current timezone to the "-d" parameter:
通过将当前时区添加到“-d”参数,您应该能够使其适用于所有时区:
s=20190201140000
date -d "${s:0:8} ${s:8:2}:${s:10:2}:${s:12:2} $(date +%Z) +1 minute" '+%Y%m%d%H%M'
20190201140100
Note 1 : All above commands are run on RHEL 7.4 & GNU bash, version 4.2.46(2)-release
注 1:以上所有命令均在 RHEL 7.4 和 GNU bash 版本 4.2.46(2)-release 上运行
Note 2 : I am sure there must be an easier way :)
注 2:我相信一定有更简单的方法:)