Blockhuette
Blockhuette

Reputation: 241

Golang date parsing malfunction

I'm trying to parse a user-input date string in the form yyyy-mm-dd (with nothing else behind) so that I can write it the same way into a file (again with nothing else behind). However the user input is not read correctly and I don't know why. Any hint would be great.

package main

import (
    "bufio"
    "fmt"
    "os"
    "time"
)

func main() {
    var datestring string
    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Startdatum im Format yyyy-mm-dd eingeben (z.B. 2018-06-24):\n")
    datestring, _ = reader.ReadString('\n')
    fmt.Printf("Type: %T, Value: %v", datestring, datestring)

    t1, _ := time.Parse("2006-01-02", datestring)   //0001-01-01 00:00:00 +0000 UTC
    t2, _ := time.Parse("2006-01-02", "2018-05-27") //2018-05-27 00:00:00 +0000 UTC
    fmt.Printf("%v\n%v\n", t1, t2)

}

Upvotes: 0

Views: 1463

Answers (2)

Blockhuette
Blockhuette

Reputation: 241

I finally came up with this solution:

package main

import (
    "bufio"
    "fmt"
    "os"
    "strings"
    "time"
)

func main() {
    // User date input
    var datestring string
    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Input start date in format yyyy-mm-dd (e.g. 2018-06-24):\n")
    datestring, _ = reader.ReadString('\n')
    datestring = strings.TrimSpace(datestring)

    // Formatted date output
    t1, err := time.Parse("2006-01-02", datestring) //0001-01-01 00:00:00 +0000 UTC
    t2 := t1.Format("2006-01-02")
    if err != nil {
        panic(err)
    }
    fmt.Printf("Result: %v\n", t2)
}

Upvotes: 0

Grokify
Grokify

Reputation: 16324

When you read datestring, it has a line feed (\n) termination character at the end. time.Parse() reads this as a parse error since it's not in your format string so you will need to handle this.

One way is to strip it off with strings.TrimSpace() as follow:

datestring, _ = reader.ReadString('\n')
datestring = strings.TrimSpace(datestring)

You can alternately add a \n to your string format, but trimming the line feed would be my preference since it uses a more standard time format string.

t1, _ := time.Parse("2006-01-02\n", datestring)

To debug this, you should handle the error from time.Parse() like so:

t1, err := time.Parse("2006-01-02", datestring) //0001-01-01 00:00:00 +0000 UTC
if err != nil {
    panic(err)
}

This will return the following error indicating there is additional text in your string. Note the closing double quote " does not immediately follow the date.

panic: parsing time "2018-06-24
": extra text: 


goroutine 1 [running]:
main.main()
    /path/to/main.go:19 +0x503
exit status 2

Upvotes: 2

Related Questions