我有一个没有时区信息的时间戳。我需要以“+02:00”格式添加时区偏移量。那么在下面的代码中,如何将偏移变量转换为“+02:00”字符串以便获得正确的 RFC3339 时间?func main() { zone, offset := time.Now().Zone() fmt.Println("zone :", zone) fmt.Println("offset :", offset ) logtimestamp := "2020-11-14 05:53:40,103" logtimestamp = strings.Split(logtimestamp, ",")[0] logtimestampFields := strings.Fields(logtimestamp) if len(logtimestampFields) > 1 { logtimestamp = logtimestampFields[0] + "T" + logtimestampFields[1] + "+02:00" //replace "+02:00" with proper offset here } formattedTime, _ := time.Parse(time.RFC3339, logtimestamp) fmt.Println("formatted timestamp " + formattedTime.Format(time.RFC3339))}
1 回答
智慧大石
TA贡献1946条经验 获得超3个赞
以下代码应该有所帮助。我已经评论了代码以便更好地理解。
package main
import (
"fmt"
"os"
"time"
)
func main() {
// Get the timezone
zone, offset := time.Now().Zone()
// Get the location
var loc = time.FixedZone(zone, offset)
// Reference format: Mon Jan 2 15:04:05 -0700 MST 2006
t, err := time.ParseInLocation("2006-01-02 15:04:05", "2020-11-14 05:53:40", loc)
if err != nil {
fmt.Println("Error: ", err)
os.Exit(1)
}
// Print the timestamp in RFC3339 format
fmt.Println(t.Format(time.RFC3339))
}
- 1 回答
- 0 关注
- 111 浏览
添加回答
举报
0/150
提交
取消