[Pro-test] Shell date time and timestamp mutual conversion

Let me talk about why I wrote this article first, because there is currently no article that allows me to successfully execute scripts on Mac.

date -dPrompts the following error on Mac:

date: option requires an argument -- d
usage: date [-jnRu] [-d dst] [-r seconds] [-t west] [-v[+|-]val[ymwdHMS]] ...
            [-f fmt date | [[[mm]dd]HH]MM[[cc]yy][.ss]] [+format]

The following timestamps are in seconds

  • Convert custom datetime to timestamp
#/bin/sh
help="?"
if [ $# != 1 ] ; then
  echo "参数为空,输入的时间格式为:2022-01-16 15:26:11"
  exit 0
elif [[ $1 = "?" ]]; then
  echo "输入的时间格式为:2022-01-16 15:26:11"
  exit 0
fi
echo "北京时间:"$1
echo "时间戳:" $(date -j -f "%Y-%m-%d %H:%M:%S" "$1" +%s)
  • Timestamp to date
#/bin/sh
echo "北京时间:"$(date -r $1)
echo "时间戳:"$1

Guess you like

Origin blog.csdn.net/stven_king/article/details/122524390