douxiaochun4964 2019-01-14 08:54
浏览 32

如何从给定日期以字符串查找工作日?

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

  • 写回答

1条回答 默认 最新

  • dqgg25493 2019-01-14 08:58
    关注

    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
    
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用