bash Linux date 命令,查找到下一小时的秒数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27595758/
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
Linux date command, finding seconds to next hour
提问by broccoli
How do I find the seconds to the next hour using date? I know I can do
如何使用日期找到下一小时的秒数?我知道我能做到
date -d "next hour"
but that just adds 1 hour to the present time. I want it to show the seconds to the next full hour. For example if the current time is 9:39am
I want to find the number of seconds to 10am
但这只是将当前时间增加了 1 小时。我希望它显示到下一个完整小时的秒数。例如,如果当前时间是9:39am
我想找到秒数10am
采纳答案by Mark Reed
Well, there's always the straightforward mathy way:
好吧,总有一种简单的数学方法:
read min sec <<<$(date +'%M %S')
echo $(( 3600 - 10#$min*60 - 10#$sec ))
EDIT:removed race condition, added explicit radix. Thanks, @rici and @gniourf_gniourf.
编辑:删除竞争条件,添加显式基数。谢谢@rici 和@gniourf_gniourf。
回答by kojiro
The epoch timestamp of right now is
现在的纪元时间戳是
now=$(date '+%s')
That of the next hour is
接下来的一个小时是
next=$(date -d $(date -d 'next hour' '+%H:00:00') '+%s')
The number of seconds until the next hour is
到下一小时的秒数是
echo $(( next - now ))
For a continuous solution, use functions:
对于连续解决方案,请使用函数:
now() { date +%s; }
next() { date -d $(date -d "next ${1- hour}" '+%H:00:00') '+%s'; }
And now you have
现在你有
echo $(( $(next) - $(now) ))
and even
乃至
echo $(( $(next day) - $(now) ))
Another way
其它的办法
Another slightly mathier approach still uses the epoch timestamp. We know it started on an hour, so the timestamp mod 3600 only equals zero on the hour. Thus
另一种稍微数学化的方法仍然使用纪元时间戳。我们知道它从一个小时开始,所以时间戳 mod 3600 只在这个小时等于 0。因此
$(( $(date +%s) % 3600 ))
is the number of seconds since the last hour, and
是自上一小时以来的秒数,以及
$(( 3600 - $(date +%s) % 3600 ))
is the number of seconds until the next.
是距离下一次的秒数。
回答by gniourf_gniourf
With Bash≥4.2 you can use printf
with the %(...)T
modifier to access dates (current date corresponds to argument -1
, or empty since version 4.3):
随着Bash≥4.2您可以使用printf
与%(...)T
修改访问日期(当前日期对应的说法-1
,或自4.3版本空):
printf -v left '%(3600-60*10#%M-10#%S)T' -1
echo "$((left))"
Pure Bash and no subshells!
纯 Bash,没有子外壳!
The 10#
is here to ensure that Bash's arithmetic (expanded in the $((...))
) treats the following number in radix 10. Without this, you'd get an error if the minute or second is 08
or 09
.
在10#
这里是为了确保 Bash 的算术(在 中扩展$((...))
)处理基数 10 中的以下数字。如果没有这个,如果分钟或秒是08
或,你会得到一个错误09
。
回答by Gilles Quenot
Try doing this :
尝试这样做:
LANG=C
now=$(date +%s)
next="$(date |
perl -pe 's/(\d{2}):\d{2}:\d{2}/sprintf "%.2d:00:00", + 1/e')"
next=$(date -d "$next" +%s)
echo $(( next - now ))
OUTPUT :
输出 :
2422
回答by porto
#!/usr/bin/env bash is=`date +%S` im=`date +%M` echo $((((60-$im)*60)+(60-$is)))