Shell时间与时间戳相换(Mac)⼀、时间戳转时间 timestamp2date.sh
1 #!/bin/sh
2
3function usage(){
4echo"-h --help \n" \
5" 将10/13位时间戳转换为本地时间 \n"\
6" 参数:时间戳,⽀持10/13位两种 \n"\
7" 默认值:当前时间向后5min \n"\
8" e.g. 1483430400(10位秒时间戳),1483430400000(13位毫秒时间戳) \n"
9 exit 1
10 }
11
12 ###
13 os_platform=`uname -s`
14if [[ $# -le 0 ]]; then
15echo"默认按照当前时间向后5min取值"
16if [[ "${os_platform}" = "Darwin" ]];then
17echo `date -v+5M +"%Y-%m-%d %H:%M:%S"`
18elif [[ "${os_platform}" = "Linux" ]];then
19echo `date -d +5min +"%Y-%m-%d %H:%M:%S"`
20fi
21else
22case $1in
23 -h|--help)
24 usage
25 ;;
26 *)
27 timestampStr=${1}
28 length=`echo ${#timestampStr}`
29if [[ ${length} -ne 10 ]] && [[ ${length} -ne 13 ]];then
30echo"请输⼊10/13位数字时间戳"
31 exit 1
32elif [[ ${length} -eq 13 ]];then
33 timestampStr=${timestampStr:0:10}
34fi
35echo"时间戳位:${timestampStr}"
36if [[ "${os_platform}" = "Darwin" ]];then
37 dateStr=`date -r${timestampStr} +"%Y-%m-%d %H:%M:%S"`
38elif [[ "${os_platform}" = "Linux" ]];then
39 dateStr=`date -d @${timestampStr} +"%Y-%m-%d %H:%M:%S"`
40fi
41echo"${1}对应的本地时间为${dateStr}"
42 ;;
43esac
44fi
命令⾏执⾏
1sh timestamp2date.sh1507704300000
2时间戳位:1507704300
3 1507704300000对应的本地时间为2017-10-1114:45:00
⼆、时间转时间戳 date2timestamp.sh
1 #!/bin/sh
2
3function usage(){
4echo"-h --help \n" \
5" 将本地时间转换为13位时间戳(毫秒时间戳) \n"\
6" 只有1个参数:本地时间,参数格式:'%Y-%m-%d %H:%M:%S' \n"\
7" 默认值:当前时间向后5min \n"\
8" e.g. 2017-01-01 16:00:00 \n"
9 exit 1
10 }
11
12
13 ##时间采⽤正则匹配
14 time_pattern="^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2} [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}"
15 os_platform=`uname -s`
16
17if [[ $# -le 0 ]]; then
18echo"默认按照当前时间向后5min取值"
19if [[ "${os_platform}" = "Darwin" ]];then
20echo `date -v+5M +%s`000
21elif [[ "${os_platform}" = "Linux" ]];then
22echo `date -d +5min +%s`000
23fi
24else
25case $1in
26 -h|--help)
27 usage
28 ;;
29 *)
30 dateStr=${1}
31echo ${dateStr}
32if [[ "${dateStr}" =~ ${time_pattern} ]];then
33if [[ "${os_platform}" = "Darwin" ]];then
34echo `date -j -f "%Y-%m-%d %H:%M:%S""${dateStr}" +%s`000
35elif [[ "${os_platform}" = "Linux" ]];then
36echo `date -d "${dateStr}" +%s`000
37fi
38else
正则匹配时间戳39echo"时间格式不正确,请按照'%Y-%m-%d %H:%M:%S'格式输⼊,如'2017-01-01 16:00:00' " 40fi
41 ;;
42esac
43fi
命令⾏执⾏
1sh date2timestamp.sh'2017-10-13 14:38:30'
22017-10-1314:38:30
31507876710000
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论