bash 如何在 UNIX 中将像“19-FEB-12”这样的字符串转换为纪元日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14805591/
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
How to convert strings like "19-FEB-12" to epoch date in UNIX
提问by hellish
In UNIX how to convert to epoch milliseconds date strings like:
在 UNIX 中如何转换为纪元毫秒日期字符串,如:
19-FEB-12
16-FEB-12
05-AUG-09
I need this to compare these dates with the current time on the server.
我需要这个来将这些日期与服务器上的当前时间进行比较。
回答by Anew
To convert a date to seconds since the epoch:
要将日期转换为自纪元以来的秒数:
date --date="19-FEB-12" +%s
Current epoch:
当前时代:
date +%s
So, since your dates are in the past:
因此,由于您的日期是过去的日期:
NOW=`date +%s`
THEN=`date --date="19-FEB-12" +%s`
let DIFF=$NOW-$THEN
echo "The difference is: $DIFF"
Using BSD's date
command, you would need
使用 BSD 的date
命令,你需要
$ date -j -f "%d-%B-%y" 19-FEB-12 +%s
Differences from GNU date
:
与 GNU 的区别date
:
-j
preventsdate
from trying to set the clock- The input format must be explicitly set with
-f
- The input date is a regular argument, not an option (viz.
-d
) - When no time is specified with the date, use the current time instead of midnight.
-j
防止date
尝试设置时钟- 输入格式必须明确设置为
-f
- 输入日期是一个常规参数,而不是一个选项(即。
-d
) - 如果日期没有指定时间,请使用当前时间而不是午夜。
回答by Steve
Here's one way using GNU awk
. To run:
这是使用GNU awk
. 跑步:
awk -f script.awk file
Contents of script.awk
:
内容script.awk
:
BEGIN {
n = systime()
FS="-"
}
{
t = mktime(sprintf("%d %d %d %d %d %d", "20" , convert(), , 0, 0, 0))
printf "%.1f days ago\n", (n - t) / 60 / 60 / 24
}
function convert(m) {
return(((index("JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC", m) - 1) / 3) + 1)
}
Results:
结果:
358.6 days ago
361.6 days ago
1286.6 days ago