Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Golang time.Date printing wrong time

Why the code below prints December 1st instead of November 31?

// You can edit this code!
// Click here and start typing.
package main

import (
    "fmt"
    "time"
)

func main() {
    ref := time.Date(2021, time.November, 31, 1, 1, 1, 1, time.UTC)

    fmt.Println(ref)

}

Run

2021-12-01 01:01:01.000000001 +0000 UTC

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Because Nov only contains 30 days. According to the source code of GO, the date will be normalized during the conversion, so it will prints December 1st instead of November 31

// Date returns the Time corresponding to
//  yyyy-mm-dd hh:mm:ss + nsec nanoseconds
// in the appropriate zone for that time in the given location.
//
// The month, day, hour, min, sec, and nsec values may be outside
// their usual ranges and will be normalized during the conversion.
// For example, October 32 converts to November 1.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading