Home > Backend Development > Golang > Use golang time.Now() to parse dates in mongoDB

Use golang time.Now() to parse dates in mongoDB

WBOY
Release: 2024-02-05 23:24:12
forward
1127 people have browsed it

使用 golang time.Now() 解析 mongoDB 中的日期

Question content

I am creating a date using go via time.now() and storing it in mongodb ,There is no problem. The date looks like 2023-02-28t20:10:46.140 00:00.

However, when I try to retrieve it, I get an error message:

{{"code":2, "message":"parsing time \"2023-02-28 20:10:46.14 +0000 utc\" as \"2006-01-02t15:04:05z07:00\": cannot parse \" 20:10:46.14 +0000 utc\" as \"t\"", "details":[]}
Copy after login

It comes from this code.

createdAt, err := time.Parse(time.RFC3339, blog.CreatedAt.String())
if err != nil {
    return nil, err
}
updatedAt, err := time.Parse(time.RFC3339, blog.UpdatedAt.String())
if err != nil {
    return nil, err
}

tempBlog := &api.Blog{
    Id: blog.ID,
    CreatedAt: timestamppb.New(createdAt),
    UpdatedAt: timestamppb.New(updatedAt),
Copy after login

I found some helpful documentation here and here and added manually parsed times to mongo, but I'm still stuck with this problem.

I have tried all time formats but it just results in different errors that cannot be parsed.

suggestion?


Correct answer


If you store time.time mongodb will automatically retrieve it for you. The time retrieved is in utc time, if you want to change to local time zone, use time.local().

package date_test

import (
    "context"
    "github.com/stretchr/testify/require"
    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
    "os"
    "testing"
    "time"
)

type something struct {
    name       string    `json:"name" bson:"name"`
    createtime time.time `json:"createtime" bson:"createtime"`
}

func testdate(t *testing.t) {
    raw := something{name: "demo", createtime: time.now()}
    t.logf("raw: %v", raw)
    ctx, cancel := context.withtimeout(context.background(), 20*time.second)
    defer cancel()
    client, err := mongo.connect(ctx, options.client().applyuri(os.getenv("uri")))
    require.noerror(t, err)
    collection := client.database("test").collection("demo")
    _, err = collection.insertone(ctx, raw)
    require.noerror(t, err)
    var res something
    err = collection.findone(ctx, bson.d{{"name", raw.name}}).decode(&res)
    require.noerror(t, err)
    t.logf("res: %v", res)
    t.logf("local time: %v", res.createtime.local())
}
Copy after login

Run the test code and it will print something like this

$ uri="mongodb://127.0.0.1:27017/" go test -v ./date_test.go
=== run   testdate
    date_test.go:21: raw: {demo 2023-03-07 10:26:22.433473 +0800 cst m=+0.009080292}
    date_test.go:32: res: {demo 2023-03-07 02:26:22.433 +0000 utc}
    date_test.go:33: local time: 2023-03-07 10:26:22.433 +0800 cst
--- pass: testdate (0.01s)
pass
ok      command-line-arguments  0.912s
Copy after login

mongo stores time like this

> db.demo.find().pretty()
{
    "_id" : ObjectId("6406a0ce4cfff0411ca8d98b"),
    "name" : "demo",
    "createTime" : ISODate("2023-03-07T02:26:22.433Z")
}
Copy after login

Source code herehttps://gist.github.com/alex-x-encryption/14c15d4921f1ece2962302cce87c97a8

The above is the detailed content of Use golang time.Now() to parse dates in mongoDB. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template