Skip to content

Instantly share code, notes, and snippets.

@nacho4d
Last active December 21, 2015 04:09
Show Gist options
  • Save nacho4d/6247276 to your computer and use it in GitHub Desktop.
Save nacho4d/6247276 to your computer and use it in GitHub Desktop.
Time Converter
#!/bin/bash
function unix_to_days_offset ()
{
echo "($1-1356966000)/(24*3600)" | bc;
}
function unix_to_human ()
{
res=`date -d @$1 "+%Y-%m-%d %H:%M:%S %Z"`;
echo $res;
unix_to_days_offset $1;
}
function human_to_unix ()
{
res=`date -d $1 '+%s'`
echo $res;
unix_to_days_offset $res
}
function usage ()
{
echo "Time converter"
echo " Converts between unix and human readable format date (like +%Y-%m-%d %H:%M:%S %Z)"
echo " Shows the number of days since 2013-01-01 00:00:00 JST"
echo " Note: It relies on GNU date command (Linux). It needs a trick to work on BSD's date (OSX)".
echo "Usage:"
echo "tc [seconds|date]"
echo "examples:"
echo "\$ tc 1375974000"
echo "> 2013-08-09 00:00:00 JST"
echo "> 220"
echo "\$ tc 2013-08-09"
echo "> 1375974000"
echo "> 220"
}
# Bad usage
if [ "$#" -ne 1 ]; then
usage
exit 1
fi
# Help option
if [ $1 == -h ]; then
usage
exit 0;
fi
# Do the conversion
date -d @$1 >& /dev/null
if [ $? == 0 ]
then
unix_to_human $1;
else
human_to_unix $1;
fi
exit 0;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment