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 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?