Get the App
SLTechnology News&Howtos  ›  Database  › 

Golang parses ISODate types in mongodb

Shulou Source: shulou.com Published: 2022-06-01 14:51:48 10月20日 Update

You can use the time.Time data type in golang to save ISODate time in mongodb.

G

Type Model struct {uploadDate time.Time `bson: "uploadDate" `} m: = Model {} if err: = c.Find (nil). Select ({"_ id": 0, "uploadDate": 1}). One (& m); err! = nil {fmt.Printf ("failed to find date, error% s\ n", err) os.Exit (1)} fmt.Printf ("% + v\ n", m)

You can see from the output that the time format of golang output is CST time zone. Golang converts ISO time into CST time in the process of processing, which is also 8 hours faster than that in mongodb from the time panel, which is normal.

So does golang need to change its own timestamp when doing insert operation or time comparison operation? The answer is no, let's take a look at the example of insertion.

Reinsert a record, the Time field of the record is the current time, and the current time can be obtained through time.Now in golang. You can see that the output is in the time format of CST.

Now: = time.Now () fmt.Printf ("% + v\ n", now) / / output: 2016-05-12 14MN 3415 00.998011694 + 0800 CSTerr = c.Insert (Model {Time: now}) if err! = nil {panic (err)}

You can see that the time stored in mongodb is automatically converted to ISO time, which is 8 hours less. To sum up, the time interaction in golang and mongodb does not need to think about anything extra, because the drivers have been converted.

Sometimes we store the time of time.Time as a string, so we need to convert time.Time format when we want to interact with mongodb.

TimeString: = "2016-05-12 14time.Parse 34time.Parse 00.998011694 + 0800 CST" t, err: = time.Parse ("2006-01-02 15purl 04VR 05.999999999-0700 MST", timeString) if err! = nil {panic (err)} fmt.Printf ("% + v\ n", t)

What is more difficult to understand in the code is the first parameter of time.Parse, which is actually defined in golang. Take a closer look at the source code of time.Time.String () and you will understand it.

Tags: Time format output hour that is time storage type thing lieutenant general code example parameter can be passed through field character string summary form data Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn Linux Shulou Information Apple Shulou Technology