sheik
sheik

Reputation: 513

How to assign the string value to time format in GO?

I have below code. I am trying to convert from string value to time format and assigning the value and failing with below error at line no:

cannot assign time.Time to psdvalue (type string) in multiple assignment

Code:

type Tracking struct {
    release_name       string
    planned_start_date time.Time
}

const layout = "01-02-2006"

func saveHandler(response http.ResponseWriter, request *http.Request) {

    releasevalue := request.FormValue("ReleaseName")
    psdvalue := request.FormValue("PSD")

    if len(strings.TrimSpace(psdvalue)) > 0 {
        //line no:              psdvalue, _ = time.Parse(layout, psdvalue)
    }

    array = append(array, Tracking{
        release_name:       releasevalue,
        planned_start_date: psdvalue,
    })

}

Upvotes: 1

Views: 1894

Answers (3)

Alex Pliutau
Alex Pliutau

Reputation: 21957

In your case error happens because you are using same var for 2 types, if you change psdvalue to something else it will work. Check here - https://play.golang.org/p/Z8_--GluMoP

package main

import (
    "fmt"
    "time"
)

func main() {
    layout := "01-02-2006"
    psdvalue := "04-04-2004"
    parsed, err := time.Parse(layout, psdvalue)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%v", parsed)
}

Also, do not forget to handle the error in Parse function.

Upvotes: 2

sberry
sberry

Reputation: 131978

time.Parse returns a time and an error. You are assigning the string portion to pdsvalue which is already declared as a string when you assign the FormValue of "PSD". psdvalue is therefore already a string type and cannot be assigned a time.Time value. Use a different variable name in your assignment (and don't swallow the error either).

Upvotes: 1

Eugene Lisitsky
Eugene Lisitsky

Reputation: 12845

You have to take both returned values:

const shortForm = "2006-Jan-02"
t, _ = time.Parse(shortForm, "2013-Feb-03")

https://golang.org/pkg/time/#Parse

Upvotes: 0

Related Questions