go发布项目后运行,报错time: missing Location in call to Time.In

go报错time: missing Location in call to Time.In,使用记录一下错误解决。

错误描述

在go代码中使用了时区

	const timezone = "Asia/Shanghai"
func TimeFormat(date time.Time, pattern string) string {
    
    
	location, err := time.LoadLocation(timezone)
	date.In(location)
	return date.Format(pattern)
}

这个时候,有些服务器、电脑上面使用time.LoadLocation会报错:time: missing Location in call to Time.In
,因为缺少文件或者配置。

解决方案

const timezone = "Asia/Shanghai"
func TimeFormat(date time.Time, pattern string) string {
    
    
	location, err := time.LoadLocation(timezone)
	if err != nil {
    
    
		location = time.FixedZone("CST", 8*3600) //替换上海时区方式
	}
	date.In(location)
	return date.Format(pattern)
}

猜你喜欢

转载自blog.csdn.net/weixin_43578304/article/details/130052623