duanbing6955 2018-06-07 18:04
浏览 302
已采纳

解析UTC日期字符串并转换为其他格式

Go newcomer here.

I have a date string 2018-06-07T16:16:57Z and I want to convert it to something like this mm/dd/yyyy hh:mm.

This seems to be a frequently asked question, but I can't seem to find any previous questions that work for me.

I'm reading in a time field and trying to convert like this

time := row["Date & Time"]
fmt.Println(time)
t, _ := time.Parse("2006-01-02 15:04:05 -0700 UTC", time)
fmt.Println(t)

But I think the issue is that I don't have a correct format string. I've tried a few resources to no success.

When I print t as is, I get 0001-01-01 00:00:00 +0000 UTC as a result, which is obviously incorrect.

What I'd like to do is convert the time I'm reading in like this

newTime := currentDate.Format("01/02/2006 hh:mm")

  • 写回答

2条回答 默认 最新

  • doumao1887 2018-06-07 18:19
    关注

    You have two issues.

    First, you should not name the variable time as that is the name of a built-in package. I suppose you knew that and this is just a copy paste error.

    Next, the string you pass to time.Parse() is a format string that should describe the format of the time string from your database. You already know what the format is: 2018-06-07T16:16:57Z, so just use that replacing the value with Go's reference time.

    Here is working variant:

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
        tm := "2018-06-07T16:16:57Z"
        fmt.Println(tm)
        t, err := time.Parse("2006-01-02T15:04:05Z", tm)
        if err != nil {
            panic(err)
        }
        fmt.Println(t)
    }
    

    Run in playground


    What's more the time format database uses is often described as RFC3339, which is also available as the time.RFC3339 constant in Go.

    So using that simplifies your code even further:

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
        tm := "2018-06-07T16:16:57Z"
        fmt.Println(tm)
        t, err := time.Parse(time.RFC3339, tm)
        if err != nil {
            panic(err)
        }
        fmt.Println(t)
    }
    

    Run in playground


    And if you prefer, you could also let the database driver convert the time for you by scanning it to a time.Time variable.

    For example:

    var tm time.Time
    if err = row.Scan(&tm); err != nil {
        panic(err)
    }
    fmt.Print(tm)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常
  • ¥15 关于风控系统,如何去选择
  • ¥15 这款软件是什么?需要能满足我的需求
  • ¥15 SpringSecurityOauth2登陆前后request不一致