Accessing MongoDB from Go: Converting MongoDB String Date to Go Time
Your code snippet reveals that you're accessing MongoDB from Go and encountering a challenge in converting MongoDB string dates to Go Time. The provided clientConfigData struct includes an EndDate field declared as a string, matching MongoDB's storage format. However, you need to access this date as a Go Time value.
Custom Marshaling and Unmarshaling
To achieve this conversion, consider implementing custom marshaling and unmarshaling logic. By implementing the bson.Getter and bson.Setter interfaces, you gain control over the value transformations during marshaling and unmarshaling processes.
Extended clientConfigData Struct
Extend the clientConfigData struct to include an additional EndDate field of type time.Time (the desired value type):
type clientConfigData struct { SMTPAssoc int `bson:"smtp_assoc"` PlanType string `bson:"plan_type"` EndDateStr string `bson:"end_date"` EndDate time.Time `bson:"-"` // bson tag "-" excludes this field from MongoDB }
Custom Marshaling and Unmarshaling Functions
Define custom marshaling and unmarshaling functions for the clientConfigData struct:
const endDateLayout = "2006-01-02 15:04:05" // Customizable date layout func (c *clientConfigData) SetBSON(raw bson.Raw) (err error) { type my clientConfigData if err = raw.Unmarshal((*my)(c)); err != nil { return } c.EndDate, err = time.Parse(endDateLayout, c.EndDateStr) return } func (c *clientConfigData) GetBSON() (interface{}, error) { c.EndDateStr = c.EndDate.Format(endDateLayout) type my *clientConfigData return my(c), nil }
Explanation
Using the New Fields
Now, you can use the EndDate field to access the date as a Go Time value. The custom marshaling and unmarshaling logic will automatically convert between the string and time formats when reading and saving data to MongoDB.
The above is the detailed content of How to Convert MongoDB String Dates to Go Time?. For more information, please follow other related articles on the PHP Chinese website!