bash 如何在脚本中将日期从 Unix 时间转换为字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9832393/
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 do I convert a date from Unix time to string, in a script?
提问by user121196
To convert a date from string to Unix time, I can use date --date "2012-02-13" +%s
.
要将日期从字符串转换为 Unix 时间,我可以使用date --date "2012-02-13" +%s
.
How do I do the opposite, from Unix time to string?
我如何做相反的事情,从 Unix 时间到字符串?
回答by mathematical.coffee
You can use date --date @datetime
:
您可以使用date --date @datetime
:
[foo@bar ~]$date --date "2012-02-13" +%s
1329055200
[foo@bar ~]$date --date @1329055200
Mon Feb 13 00:00:00 EST 2012
[foo@bar ~]$date --date @1329055200 +"%Y-%m-%d"
2012-02-13
I'm not sure where the '@xxxx' is documented though!
不过,我不确定“@xxxx”的记录在哪里!
回答by ghoti
The options to the date
command depend on your operating system.
date
命令的选项取决于您的操作系统。
In FreeBSD:
在 FreeBSD 中:
[ghoti@pc ~]$ date -r 1332468005 '+%Y-%m-%d %T'
2012-03-22 22:00:05
In Linux:
在 Linux 中:
ghoti@wopr$ date -d @1332468005 '+%Y-%m-%d %H:%M:%S'
2012-03-22 22:00:05
In other operating systems, I don't know.
在其他操作系统中,我不知道。
If you want a solution that doesn't rely on the date
command, you can use perl or gawk, if they happen to be installed on the machine you're using.
如果您想要一个不依赖于date
命令的解决方案,您可以使用 perl 或 gawk,如果它们恰好安装在您使用的机器上。
ghoti@wopr$ gawk -v when=1332468005 'BEGIN{ print strftime("%Y-%m-%d %T", when); }'
2012-03-22 22:00:05
回答by Jasonw
Use the --date=@
option to pass the Unix timestamp, and use the format according to the output you want.
使用--date=@
选项传递 Unix 时间戳,并根据您想要的输出使用格式。
$ date --date "2012-02-13" +%s
1329062400
$ date --date=@1329062400 +%F
2012-02-13
回答by FatalError
It can be done through awk
:
它可以通过awk
:
$ date --date "2012-02-13" +%s | awk '{ print strftime("%Y-%m-%d", ); }'
2012-02-13
or any other tool that provides an interface to strftime()
或任何其他提供接口的工具 strftime()