I have a function in my app that saves the date in string into the database, but it can't save the day on that date. I have tried a short code on this. Suppose we have a date in string.
Code:
package main
import (
"fmt"
"strconv"
"strings"
"time"
)
func main() {
p := fmt.Println
date := "01-25-2019"
arrayDate := strings.Split(date, "-")
fmt.Println(arrayDate)
month, _ := strconv.Atoi(arrayDate[0])
dateInt, _ := strconv.Atoi(arrayDate[1])
year, _ := strconv.Atoi(arrayDate[2])
then := time.Date(
year, time.Month(month), dateInt, 0, 0, 0, 0, time.UTC)
p(then)
p(then.Weekday())
}
Is there any more efficient way to do this?
playground link
Yes, simply parse the time using time.Parse()
, e.g.
date := "01-25-2019"
t, err := time.Parse("01-02-2006", date)
if err != nil {
panic(err)
}
fmt.Println(t.Weekday())
time.Parse()
will do the parsing that you tried to implement manually. Note that the first parameter to time.Parse()
is a layout string, it must contain a reference time (which is Mon Jan 2 15:04:05 -0700 MST 2006
) in the format your input is given.
Output (try it on the Go Playground):
Friday