cat*_*ter 1 string time date go weekday
我的应用程序中有一个函数将字符串中的日期保存到数据库中,但它无法保存该日期的那一天.我试过一个简短的代码.假设我们在字符串中有一个日期.
码:
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())
}
Run Code Online (Sandbox Code Playgroud)
有没有更有效的方法来做到这一点?
游乐场链接
是的,只需使用time.Parse()例如解析时间
date := "01-25-2019"
t, err := time.Parse("01-02-2006", date)
if err != nil {
panic(err)
}
fmt.Println(t.Weekday())
Run Code Online (Sandbox Code Playgroud)
time.Parse()将执行您尝试手动实现的解析.请注意,第一个参数time.Parse()是布局字符串,它必须包含Mon Jan 2 15:04:05 -0700 MST 2006您输入的格式的参考时间(即).
输出(在Go Playground上试试):
Friday
Run Code Online (Sandbox Code Playgroud)