Reputation: 193
I tried to parsing string to time in go, here is what I've done:
dateTime := fmt.Sprintf("%s %s CST", dateValue, timeValue)
date, err := time.Parse("2006-1-2 150405 MST", dateTime)
I got the following error message:
parsing time "2012-4-9 174031 CST" as "2006-1-2 150405 MST": cannot parse "2012-4-9 174031 CST" as "2006"
From the error message, it shows the dateTime
value I passed in is correct. I also tried to do the following, it works fine:
dateTime := "2012-4-9 174031 CST"
date, err := time.Parse("2006-1-2 150405 MST", dateTime)
This is bothering me for a few days. Could anybody help to point out where is the mistake? Thanks!
Upvotes: 0
Views: 750
Reputation: 9653
Your values are not as you expect. I suspect you have whitespace in one or more values. Here is an example to play with which produces the same error (note the leading space on dateValue):
https://play.golang.org/p/UwKhjQs6Nig
dateValue := " 2012-4-9"
timeValue := "174031"
dateTime := fmt.Sprintf("%s %s CST", dateValue, timeValue)
date, err := time.Parse("2006-1-2 150405 MST", dateTime)
The first step if you ever hit a problem like this is to print your values before using them to verify they are exactly as you expect. If posting for help, also try to reproduce it on play.golang.org - often the process of doing this will help you finding the problem yourself.
The error message could be better, but I suspect what it is doing is taking the first part of the format (year), attempting to find it in the string value and failing, hence the report of not finding 2006.
Upvotes: 1