dongqiu3254 2016-12-02 19:02
浏览 91
已采纳

Golang解析奇怪的日期格式

I'm working on a Parser which Parses log files from a game so I can do analysis on auctions made within the game, however the date format that's being written by the logger seems to be causing problems as the format seems to be custom written for the logger, an example datetime stamp looks like: [Wed Nov 23 23:26:10 2016] I try to Parse it with:

func (r *AuctionReader) extractSaleInformation(line string) {
    fmt.Println("Extracting information from: ", line)

    // Format mask for output
    layout := "DD-MM-YYYY hh:mm:ss"

    // Replace the square brackets so we're just left with the date-time string
    date := strings.TrimSpace(strings.Replace((strings.Split(line, "]")[0]), "[", "", -1))

    fmt.Println(time.Parse(date, layout))
}

When I attempt to Parse the above date-time string I get the following error:

0001-01-01 00:00:00 +0000 UTC parsing time "DD-MM-YYYY hh:mm:ss" as "Wed Nov 23 23:26:10 2016": cannot parse "DD-MM-YYYY hh:mm:ss" as "Wed Nov "

How am I able to get the parser to recognise this seemingly custom format, I will be saving this data to Mongo so I don't want to store the auction time as a string as I want to query the timestamps individually.

  • 写回答

1条回答 默认 最新

  • dtrvzd1171 2016-12-02 19:10
    关注

    Golang handle all date formatting in a unique way - it uses the reference time Mon Jan 2 15:04:05 MST 2006 (01/02 03:04:05PM '06 -0700) to show the pattern with which to format/parse a given time/string.

    So, to read the format "Wed Nov 23 23:26:10 2016" you would put the reference date into that format: "Mon Jan 2 15:04:05 2006", and then do:

    t, _ := time.Parse("Mon Jan 2 15:04:05 2006", "Wed Nov 23 23:26:10 2016")
    

    Then, to output it in the given format, if you wanted the format DD-MM-YYYY hh:mm:ss, you would put the reference time into that format: 02-01-2006 15:04:05, and then do:

    t.Format("02-01-2006 15:04:05")
    

    https://play.golang.org/p/VO5413Z7-z

    So basically, the main change is

    // Format mask for output
    layout := "DD-MM-YYYY hh:mm:ss"
    

    should be

    // Format mask for output
    layout := "02-01-2006 15:04:05"
    

    and

    time.Parse(date, layout)
    

    should be

    time.Parse(layout, date)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?