douyi9447 2015-07-01 15:24
浏览 157
已采纳

前往:time.Parse()问题

I have the following code:

timeLocal := "01/July/2015:18:12:25 +0900"
inFormat := "02/January/2006:15:04:05 -0700"
parsed, err := time.Parse(inFormat, timeLocal)
if err != nil {
    log.Fatal("Time format was not recognized!")
}

Now, parsing works fine. But when I run:

fmt.Println(timeLocal)
fmt.Println(inFormat)
fmt.Println(parsed)

The output is:

01/July/2015:18:12:25 +0900
02/January/2006:15:04:05 -0700
2015-07-01 18:12:25 +0900 +0900

Should the second +0900 be there? What is the stupid thing that I'm doing? Sorry, it was really a long day, I don't see what I'm missing.

Oh, and the whole file is here:

package main

import (
    "fmt"
    "time"
    "log"
)

func main() {
    timeLocal := "01/July/2015:18:12:25 +0900"
    inFormat := "02/January/2006:15:04:05 -0700"
    parsed, err := time.Parse(inFormat, timeLocal)
    if err != nil {
        log.Fatal("Time format was not recognized!")
    }

    fmt.Println(timeLocal)
    fmt.Println(inFormat)
    fmt.Println(parsed)
}
  • 写回答

2条回答 默认 最新

  • dongyue9864 2015-07-01 15:36
    关注

    If you look at documentation of time.Time you will see what the default output format is:

    String returns the time formatted using the format string:

    "2006-01-02 15:04:05.999999999 -0700 MST"

    Now you should see what the second +0900 is doing there – this is a location (time zone) name. Since your input format doesn't have a name it will simply repeat an offset.

    You can provide name by altering your input format to parse location name. Alternatively you can provide an output format which doesn't print the name, if you don't need it.

    Your modified example:

    package main
    
    import (
        "fmt"
        "time"
        "log"
    )
    
    func main() {
        timeLocal := "01/July/2015:18:12:25 +0900 XYZ"
        inFormat := "02/January/2006:15:04:05 -0700 MST"
        parsed, err := time.Parse(inFormat, timeLocal)
        if err != nil {
            log.Fatal("Time format was not recognized!")
        }
    
        fmt.Println(timeLocal)
        fmt.Println(inFormat)
        fmt.Println(parsed) // 2015-07-01 18:12:25 +0900 XYZ
        fmt.Println(parsed.Format("02/January/2006:15:04:05 -0700"))
    }
    

    http://play.golang.org/p/xVGvlt-M5B

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集