用法
参数说明
- -z,时区,默认是东八区,可以使用负号,作为西几区
- -t,时间戳,默认是当前时间
使用实例
默认无参,输出当前时间,时区是东八区
> .\time
2023-05-07 18:34:15
没有时间戳参数,输入时区参数
> .\time -z -8
2023-05-07 02:35:27
把某个时间戳转为某个时区的时间
> .\time -z -8 -t 1682455308
2023-04-25 12:41:48
源代码
package main
import (
"flag"
"fmt"
"strconv"
"time"
)
func main() {
// 定义命令行参数
name := flag.String("z", "8", "时区")
msStr := flag.String("t", "0", "时间戳")
// 解析命令行参数
flag.Parse()
zone, _ := strconv.ParseInt(*name, 10, 32)
ms, _ := strconv.ParseInt(*msStr, 10, 32)
var timestamp int64
if ms == 0 {
// 获取当前时间的时间戳(秒)
timestamp = time.Now().Unix()
} else {
timestamp = ms
}
// 转换为对应时区的时间
cstLocation := time.FixedZone("CST", int(zone*3600)) // 创建-08时区
t := time.Unix(timestamp, 0).In(cstLocation) // 将时间戳转为-08时区时间
// 格式化输出时间
fmt.Println(t.Format("2006-01-02 15:04:05"))
}
编译
go build -o time.exe xxx.go