golang时间问题汇总(用法&常见问题:插入数据库时间自动+8)

golang时间问题汇总(用法&常见问题)

1 用法

1.1 time.Parse()

func main() {

	timeStr := "2023-09-26 20:56:23"
	allDate, _ := time.Parse("2006-01-02 15:04:05", timeStr)
	fmt.Println("全部解析=", allDate) 

	timeStr = "2023-09-26 20:56:00"
	miDate, _ := time.Parse("2006-01-02 15:04:00", timeStr)
	fmt.Println("解析到分钟=", miDate)

	timeStr = "2023-09-26 20:00:00"
	hDate, _ := time.Parse("2006-01-02 15:00:00", timeStr)
	fmt.Println("解析到小时=", hDate)
	/*
	运行结果:
	全部解析= 2023-09-26 20:56:23 +0000 UTC
	解析到分钟= 2023-09-26 20:56:00 +0000 UTC
	解析到小时= 2023-09-26 20:00:00 +0000 UTC
	*/
}

1.2 time.ParseInLocation()

func main() {
	//带有时区解析
	timeStr := "2023-09-26 20:56:23"
	date, _ := time.ParseInLocation("2006-01-02 15:04:05", timeStr, time.Local)
	//loc, _ := time.LoadLocation("Asia/Shanghai")
	//date, _ := time.ParseInLocation("2006-01-02 15:04:05", timeStr, loc)
	
	//结果: 由于time.Local会匹配我们本地时区所以在这里和我们指定时区效果一样
	//date= 2023-09-26 20:56:23 +0800 CST
	fmt.Println("带有时间区间解析之后, date=", date)
}

1.3 Truncate()、Add()、Sub()

func main() {
	timeStr := "2023-09-26 20:56:23"
	date, _ := time.ParseInLocation("2006-01-02 15:04:05", timeStr, time.Local)
	fmt.Println("before truncate hour, date=", date)
	date = date.Truncate(time.Hour)
	fmt.Println("after truncate, date=", date)
	date = date.Add(time.Duration(-2) * time.Hour)
	fmt.Println("sub 2 hour, date=", date)
	date = date.Add(time.Hour * 2)
	fmt.Println("add 3 hour, date=", date)
	/*
		before truncate hour, date= 2023-09-26 20:56:23 +0800 CST
		after truncate, date= 2023-09-26 20:00:00 +0800 CST
		sub 2 hour, date= 2023-09-26 18:00:00 +0800 CST
		add 3 hour, date= 2023-09-26 20:00:00 +0800 CST
	 */


	start, _ := time.Parse("2006-01-02 15:04:05", "2023-09-25 20:56:23")
	end, _ := time.Parse("2006-01-02 15:04:05", "2023-09-27 20:56:23")
	duration := end.Sub(start)
	//相差时间:48h0m0s
	fmt.Println("duration=", duration) 

}

2 常见问题

2.1 插入数据库之后时间会自动+8

原因:时区问题,在通过xorm操作mssql时,插入之前是10:00,但是插入数据库之后变成了18:00;观察sql也发现时间由10:00变成了18:00

  • 在golang中可以通过time.ParseInLocation指定时区来解决
func main() {
	timeStr := "2023-09-26 20:56:23"
	date, _ := time.ParseInLocation("2006-01-02 15:04:05", timeStr, time.Local)
	// date= 2023-09-26 20:56:23 +0800 CST
	fmt.Println("加载指定时区, date=", date)
	//或者手动修复时区,手动修补时间
	local := time.FixedZone("CST", 8*3600)
	now := time.Now().In(local).Format("2006-01-02 15:04:05")
	// 2023-09-26 22:59:09
	fmt.Println("now=", now)
}

你可能感兴趣的:(go,数据库,golang,时区问题,time操作)