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条)

报告相同问题?

悬赏问题

  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题