go 语言时间处理报错 panic time missing Location in call to ...

在golang 使用“Asia/Shanghai” 时区转换时间格式,本机正常,其他机器报错panic time missing Location in call to ...

这是由于缺少IANA TimeZone Database,一般在linux系统都自带了,但是在window系统中可能会缺失。

实例错误代码:

func Time2Timestamp (datetime string)int64{
	//时间 to 时间戳
	loc, err := time.LoadLocation("Asia/Shanghai")        //设置时区
	rt := strings.Index("/", datetime)
	if rt ==-1{
		tt, _ := time.ParseInLocation("2006/01/02 15:04:05", datetime, loc) //2006-01-02 15:04:05是转换的格式如php的"Y-m-d H:i:s"
		return tt.Unix()*1000
	}
	tt, _ := time.ParseInLocation("2006-01-02 15:04:05", datetime, loc) //2006-01-02 15:04:05是转换的格式如php的"Y-m-d H:i:s"
	ret := tt.Unix()*1000
	return ret
}

解决方法:time.FixZone()

func Time2Timestamp (datetime string)int64{
	//时间 to 时间戳
	loc, err := time.LoadLocation("Asia/Shanghai")        //设置时区
	if err !=nil{
		loc = time.FixedZone("CST",8*3600)
	}
	rt := strings.Index("/", datetime)
	if rt ==-1{
		tt, _ := time.ParseInLocation("2006/01/02 15:04:05", datetime, loc) //2006-01-02 15:04:05是转换的格式如php的"Y-m-d H:i:s"
		return tt.Unix()*1000
	}
	tt, _ := time.ParseInLocation("2006-01-02 15:04:05", datetime, loc) //2006-01-02 15:04:05是转换的格式如php的"Y-m-d H:i:s"
	ret := tt.Unix()*1000
	return ret
}

猜你喜欢

转载自blog.csdn.net/qq_48626761/article/details/128001444