将 Unix 时间戳转换为日期字符串 [英] Convert Unix timestamp to a date string
问题描述
是否有一种快速、单行的方法可以从 Unix 命令行将 Unix 时间戳转换为日期?
Is there a quick, one-liner way to convert a Unix timestamp to a date from the Unix command line?
date
可能有用,但指定每个元素(月、日、年、小时等)相当尴尬,而且我不知道如何让它正常工作.似乎有更简单的方法 — 我是不是遗漏了什么?
date
might work, except it's rather awkward to specify each element (month, day, year, hour, etc.), and I can't figure out how to get it to work properly. It seems like there might be an easier way — am I missing something?
推荐答案
使用 GNU 的 date
你可以做到:
With GNU's date
you can do:
date -d "@$TIMESTAMP"
# date -d @0
Wed Dec 31 19:00:00 EST 1969
(来自:BASH:将 Unix 时间戳转换为日期)
在 OS X 上,使用 date -r
.
On OS X, use date -r
.
date -r "$TIMESTAMP"
或者,使用 strftime()
.它不能直接从 shell 获得,但您可以通过 gawk 访问它.%c
说明符以区域设置相关的方式显示时间戳.
Alternatively, use strftime()
. It's not available directly from the shell, but you can access it via gawk. The %c
specifier displays the timestamp in a locale-dependent manner.
echo "$TIMESTAMP" | gawk '{print strftime("%c", $0)}'
# echo 0 | gawk '{print strftime("%c", $0)}'
Wed 31 Dec 1969 07:00:00 PM EST
这篇关于将 Unix 时间戳转换为日期字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!