Earlier quoted context omitted.
Get print the current time as as Unix timestamp. date +%s To convert a Unix timestamp to local time with GNU date, e.g. date -d @1651483224 With BSD date, e.g. date -r 1651483224
Yes, I can never remember that. It's faster to just go to some online tool than to look up how to convert timestamps with `date`. Especially since I often switch between Linux and "BSD" (macOS). Something like this would be nice: $ datez 1651483224 human-readable-timestamp $ datez human-readable-timestamp 1651483224
I just gave it a try now, as a shell script:
#!/bin/sh
# https://news.ycombinator.com/item?id=31233092
case "$1" in
-*|"")
echo "Usage: datez "
;;
*)
if date -r "$1" 2>/dev/null; then date -r "$1"; else date -d "@$1"; fi
esac
Edit: tried to add the reverse, from human-readable-timestamp to Unix timestamp, and got a problem when the locale does not use the English language: the human-readable form is not understood by date as input!So the round-tripping version of the script has to set the locale to C:
#!/bin/sh
# https://news.ycombinator.com/item?id=31233092
# Needed for round-tripping:
export LANG=C
case "${1}" in
-*|"")
echo "Usage: datez "
;;
*)
case "${1}" in
(*[!0-9]*)
date -d "${1}" +"%s"
;;
(*)
if date -r "${1}" 2>/dev/null; then
date -r "${1}"
else
date -d "@${1}"
fi
esac
esac
Edit 2: it does round-trip by using a locale-independent format like "%Y-%m-%d %H:%M:%S %Z", which is anyhow the format I prefer: #!/bin/sh
# https://news.ycombinator.com/item?id=31233092
# Needed for round-tripping if you use a locale-dependant format:
#export LANG=C
FORMAT="%Y-%m-%d %H:%M:%S %Z"
case "${1}" in
-*|"")
echo "Usage: datez "
;;
*)
case "${1}" in
(*[!0-9]*)
date -d "${1}" +"%s"
;;
(*)
if date -r "${1}" 2>/dev/null; then
date -r "${1}" +"'${FORMAT}'"
else
date -d "@${1}" +"'${FORMAT}'"
fi
esac
esac