dromara / carbon

A simple, semantic and developer-friendly golang package for time
https://pkg.go.dev/github.com/golang-module/carbon/v2
MIT License
4.77k stars 238 forks source link

My local time is Asia/Shanghai, But the time from the database is UTC #208

Closed huayi closed 9 months ago

huayi commented 9 months ago

my local time is Asia/Shanghai my struct is:

type LogAccess struct {
    Id       string        `json:"id" xorm:"pk"`
    Username string        `json:"username"`
    AccessAt carbon.Carbon `json:"access_at"`
}

use xorm get AccessAt is a UTC time I changed AccessAt type to time.Time, I get a CST time What should I do to get a CST time

weifox1990 commented 9 months ago

Send complete code

huayi commented 9 months ago

complete code:

import (
    "fmt"
    "github.com/golang-module/carbon/v2"
    "testing"
    "time"
    "xorm.io/xorm"
)

type LogAccess struct {
    Id       string        `xorm:"id pk" json:"id"`
    AccessAt carbon.Carbon `json:"access_at"`
    LogoutAt time.Time     `json:"logout_at"`
}

func TestGet(t *testing.T) {
    var err error
    driver := "mssql"
    source := "server=192.168.2.xxx;port=1433;user id=xx;password=xxx;database=xxx"
    db, err = xorm.NewEngine(driver, source)
    if err != nil {
        fmt.Println(err.Error())
    }
    db.ShowSQL(true)
    db.DatabaseTZ = time.Local
    db.TZLocation = time.Local
    acc := &LogAccess{}
    db.ID("1").Get(acc)
    fmt.Println("carbon time:", acc.AccessAt)
    fmt.Println("carbon loc: ", acc.AccessAt.Location())
    fmt.Println("time.Time:", acc.LogoutAt)
}

print:

== RUN   TestGet
[xorm] [info]  2023/12/30 09:01:31.904778 [SQL] SELECT [id], [access_at], [logout_at] FROM [log_access] WHERE [id]=? ORDER BY [id] ASC OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY [1] - 151.112768ms
carbon time: 2023-12-29 23:56:46
carbon loc:  UTC
time.Time: 2023-12-29 23:56:46 +0800 CST
--- PASS: TestGet (5.62s)
weifox1990 commented 9 months ago
c := acc.AccessAt.SetTimezome("PRC")
fmt.Println("carbon time:", c)
fmt.Println("carbon loc: ", c.Location())
Issues-translate-bot commented 9 months ago

The issue body's language is not English, translate it automatically, please use English next time. πŸ‘―πŸ‘­πŸ»πŸ§‘β€πŸ€β€πŸ§‘πŸ‘«πŸ§‘πŸΏβ€πŸ€β€πŸ§‘πŸ»πŸ‘©πŸΎβ€πŸ€β€πŸ‘¨πŸΏπŸ‘¬πŸΏ


fmt.Println("carbon loc: ", acc.AccessAt.SetTimezome("PRC").Location())
huayi commented 9 months ago

Thank you. This method is indeed effective. In fact, I want it to default to using the local time zone. I think it would be better if it were set to local time by default in database function func (c *Carbon) Scan(v interface{}). Thank you again.

gouguoyin commented 9 months ago

Feat in v2.3.2 and v2.3.2 Released