I sometimes find myself wanting a Unix timestamp, or to convert one into a human-readable date, and usually it's simpler to go to an online tool than use time(1).
It might be nice to have a command line tool which can guess from the arguments what you want it to do. For example, if you run it with no arguments, it would output the current timestamp (to multiple levels of precision, listing the languages/platforms that typically use each one).
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:
Had never thought of building such a tool, but now that you mention it, there were cases where I had Unix sitmestamps in log/debug files for instance. I ended up using the web browser console to do a quick conversion.
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 <unix-timestamp>"
;;
*)
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 <unix-timestamp|human-readable-timestamp>"
;;
*)
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 <unix-timestamp|human-readable-timestamp>"
;;
*)
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
I always forget how to get a unixtime so I either load a repl or the manpage for date, but FreeBSD date -r 123 works to go to human time. date -u -r 123 if you want UTC.
It might be nice to have a command line tool which can guess from the arguments what you want it to do. For example, if you run it with no arguments, it would output the current timestamp (to multiple levels of precision, listing the languages/platforms that typically use each one).