4

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

icza
  • 389,944
  • 63
  • 907
  • 827
catter
  • 151
  • 2
  • 16
  • 3
    1. parse the date with [`time.Parse`](https://golang.org/pkg/time/#Parse), 2. call the [`Weekday`](https://golang.org/pkg/time/#Time.Weekday) method on it. – Jonathan Hall Jan 14 '19 at 08:58
  • 1
    Not related to your question, but your use of `p := fmt.Println` is a bit peculiar. I'd strongly encourage you _not_ to do that, because it makes your code hard to read. But of course, that's just my opinion. – Jonathan Hall Jan 14 '19 at 09:07
  • 1
    I'm voting to close this question as off-topic because it is just code review. – Volker Jan 14 '19 at 09:09

1 Answers1

11

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
icza
  • 389,944
  • 63
  • 907
  • 827