[Solved] Time precision issue on comparison in mongodb driver in Go and possibly in other language and other database


Times in BSON are represented as UTC milliseconds since the Unix epoch (spec). Time values in Go have nanosecond precision.

To round trip time.Time values through BSON marshalling, use times truncated to milliseconds since the Unix epoch:

func truncate(t time.Time) time.Time {
    return time.Unix(0, t.UnixNano()/1e6*1e6)
}

...

u := user{
    Username:          "test_bson_username",
    Password:          "1234",
    UserAccessibility: "normal",
    RegisterationTime: truncate(time.Now()), 
}

You can also use the Time.Truncate method:

u := user{
    Username:          "test_bson_username",
    Password:          "1234",
    UserAccessibility: "normal",
    RegisterationTime:  time.Now().Truncate(time.Millisecond),
}

This approach relies on the fact that Unix epoch and Go zero time differ by a whole number of milliseconds.

2

solved Time precision issue on comparison in mongodb driver in Go and possibly in other language and other database