doutang2382
2014-06-25 06:45
浏览 193
已采纳

time.parse:golang为什么会错误地解析时间?

I'm trying to parse a string as time with but unfortunately go gets the wrong month ( January instead of June)

package main

import "fmt"
import "time"

func main() {

    t := "2014-06-23T20:29:39.688+01:00"
    tc, _ := time.Parse("2006-01-02T15:04:05.000+01:00", t)

    fmt.Printf("t was %v and tc was %v", t, tc)

}

Play

图片转代码服务由CSDN问答提供 功能建议

我正在尝试解析字符串作为时间,但不幸的是得到错误的月份(一月而不是六月)

 包main 
 
import  “ fmt” 
import“ time” 
 
func main(){
 
t:=“ 2014-06-23T20:29:39.688 + 01:00” 
 tc,_:= time.Parse(“ 2006  -01-02T15:04:05.000 + 01:00“,t)
 
 fmt.Printf(” t为%v,tc为%v“,t,tc)
 
} 
   
 
 

播放

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • drne47241 2014-06-25 07:00
    已采纳

    The problem is that your timezone offset is ill-defined in the layout: the reference offset is -0700. You defined yours as +01:00, so the 01 is interpreted as the month and erase the previously defined one. And as your working offset is 01 as well, it is parsed as january.

    The following example works for me playground

    package main
    
    import "fmt"
    import "time"
    
    func main() {
    
        t := "2014-06-23T20:29:39.688+01:00"
        tc, _ := time.Parse("2006-01-02T15:04:05.000-07:00", t)
    
        fmt.Printf("t was %v and tc was %v", t, tc)
    
    }
    
    点赞 打赏 评论
  • duancai1904 2014-06-25 07:02

    Your layout string is incorrect. The numbers in the layout string have special meanings, and you are using 1 twice: once in the month portion and once in the time zone portion. The time zone in the string you are parsing is 01:00, so you are storing 1 into the month. This explains why the returned month was January (the first month).

    A corrected layout string is 2006-01-02T15:04:05.000-07:00. Or, if you're happy with using Z to represent UTC, the time.RFC3339 constant might be appropriate.

    点赞 打赏 评论

相关推荐 更多相似问题