grafeno30
grafeno30

Reputation: 529

How I insert a time-date-stamp in MongoDB with a Golang Sruct?

I have the following struct:

type TypeIncidence struct { Number int bson:"number" json:"number" Description string bson:"description" json:"description" Date_time_stamp string bson:"dateTimeStamp" json:"date_time_stamp" }

and I want insert a document in a collection:

type TypeIncidence struct {
    Number      int    `bson:"number" json:"number"`
    Description string `bson:"description" json:"description"`
    Date_time_stamp **string?**
}


var incidence TypeIncidence

incidence.Number = 1
Description =" Text"
Date_time_stamp = **string?**

What data type would I have to use in a Golang structure to store date_time_struct a string?

If I want to store with the following format 'YYYY-MM-DD hh:mm:ss', what module and/or function should I use in golang? (in local machine or server converting zone time)

Thanks in advance

Upvotes: 0

Views: 1876

Answers (1)

Stefan Zhelyazkov
Stefan Zhelyazkov

Reputation: 2981

You can use time.Time:

CreatedAt time.Time `json:"created_at" bson:"created_at"`

However, I would recommend that you store Epoch Unix timestamp (the number of seconds since Jan 1st 1970) because it is universal:

CreatedAt int64 `json:"created_at" bson:"created_at"`

I have tried in the past to store time.Time in MongoDB through Golang but then I had trouble when I parsed the same information into a datetime object in Python. If you would like to be compatible across languages and technologies, storing the Epoch Unix timestamp would be a great option.

Upvotes: 3

Related Questions