How to parse 0000-00-00 00:00:00?

I am parsing some time values ​​from mysql database, and some of them are null. Why can't Go analyze this and how to fix it?

checkTime := "0000-00-00 00:00:00" t, err := time.Parse("2006-01-02 15:04:05", checkTime) if err !=nil{ log.Errorf("err %v, checkTime %v, ID %v", err, checkTime, bk.ID) } 

I get:

 err parsing time "0000-00-00 00:00:00": month out of range, checkin 0000-00-00 00:00:00 
+5
source share
3 answers

This is not analyzed because there was no zero year. After 1 BC 1 AD

In most contexts, it probably makes sense to do a special check for year zero and keep NULL in place.


From a practical point of view, any dates indicated as a year between 1 A.D. and about 600 AD, poorly documented and probably erroneous. Somewhere there are a few missed years. Scientists do not know how much, but they basically agree that at least 4 years have gone missing and possibly as many as 8 or 10. That is, 2015 should actually be from 2019 to 2029.

+5
source

First, a compile-time error occurs in your code: there is no function log.Errorf() (that is, if you use standard log ). Instead, use, for example, log.Printf() .

Secondly, since your error indicates: month out of range . The month is in the range if 1..12 . Month value 0 or 00 invalid. See valid months here .

Zero time (or a more precise term: zero value of type time.Time ) is printed as follows:

 log.Println("Zero time is:", time.Time{}.Format("2006-01-02 15:04:05")) 

Output:

 2009/11/10 23:00:00 Zero time is: 0001-01-01 00:00:00 

Please note that year, month and day are all 1 .

Also note that even if days start at 1 , day 0 also accepted and interpreted as -1 day from the first day of the month indicated in parts of the year and month.

So, while "0000-01-01 00:00:00" can be analyzed and correctly gives "0000-01-01 00:00:00 +0000 UTC" , the time is "0000-01-00 00:00:00" will give "-0001-12-31 00:00:00 +0000 UTC" .

The exact date "0000-00-00 00:00:00" represents the zero date from your source (MySql db?), And so in Go, when that date is found, I would return a zero value for Go time.Time so that you could test it using Go with the Time.IsZero() method. Use this simple helper function to analyze your times:

 func parseTime(s string) (time.Time, err) { if s == "0000-00-00 00:00:00" { return time.Time{}, nil } return time.Parse("2006-01-02 15:04:05", s) } 

See examples in action on the Go Playground .

+4
source

Zero value of type Time January 1, year 1, 00: 00: 00.00.000000000 UTC . So there is no month 0 in Go.

+1
source

All Articles