bash 如何将bash字符串转换为日期?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27401197/
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 a bash string into a date?
提问by Claude Lag
I have a file which contains a string:
我有一个包含字符串的文件:
2014-11-22 08:15:00
... which represents Nov 22 2014 @ 8:15 AM
.
... 代表Nov 22 2014 @ 8:15 AM
.
I want to parse this string and use it with the date function in BASH to compare with the current date. I have code that compares dates but both dates are generated by BASH and it's easy to format and compare. However, I can't use the string (which is collected from another system) to compare.
我想解析这个字符串并将其与 BASH 中的日期函数一起使用以与当前日期进行比较。我有比较日期的代码,但两个日期都是由 BASH 生成的,并且很容易格式化和比较。但是,我无法使用字符串(从另一个系统收集)进行比较。
I've tried stuff like:
我试过这样的东西:
$ mydate=$(cat filewithstring);date -d $mydate
$ mydate=$(cat filewithstring);date -d '$mydate'
$ mydate=$(cat filewithstring);date -d $mydate "+%Y-%m-%d %H:%M:%S"
I end up with errors like:
我最终遇到如下错误:
date: the argument ‘08:00:00' lacks a leading '+'; when using an option to specify date(s), any non-option argument must be a format string beginning with '+'*
日期:参数“08:00:00”缺少前导“+”;使用选项指定日期时,任何非选项参数必须是以 '+'* 开头的格式字符串
...or...
...或者...
date: extra operand ‘+%Y-%m-%d %H:%M:%S'
日期:额外的操作数 '+%Y-%m-%d %H:%M:%S'
I know that if I type in the string explicitly, it works fine:
我知道如果我明确输入字符串,它工作正常:
$ date -d '2014-11-22 08:15:00'
Sat Nov 22 08:15:00 EST 2014
In the end, I'm hoping to do the following:
最后,我希望做到以下几点:
- capture and collect the date/time string in the file from the "other" server
- read the string in the file
- compare that date/time in the string with the current date/time
- output something like "This event processed 12 minutes ago"
- 从“其他”服务器捕获并收集文件中的日期/时间字符串
- 读取文件中的字符串
- 将字符串中的日期/时间与当前日期/时间进行比较
- 输出类似“此事件在 12 分钟前处理过”之类的内容
Any ideas? Thanks.
有任何想法吗?谢谢。
回答by fedorqui 'SO stop harming'
This is because you are using single quotes, so that the value of the variable is not expanded.
这是因为您使用的是单引号,因此不会扩展变量的值。
You can say:
你可以说:
mydate=$(<filewithstring)
date -d"$mydate" "+%Y-%m-%d %H:%M:%S"
^ ^
Note also mydate=$(<filewithstring)
is a more optimal way to read the file into a variable.
注意也是mydate=$(<filewithstring)
将文件读入变量的更佳方法。