如何在GO中解析简单的从大到小的日期字符串

huangapple go评论74阅读模式
英文:

How to parse simple biggest to smallest date string in GO

问题

我正在尝试学习Go语言,它是一种非常有趣的语言。我有一堆文本文件,我们需要在其中运行导入操作,日期的格式是YYYYMMDDHHmm。我该如何将其解析为内部日期格式?以下代码无法正常工作:

package main

import "fmt"
import "time"

func main() {
    t, err := time.Parse("YYYYMMDDHHmm", "201302031010")
    fmt.Println(t)

    if err != nil {
        panic(err)
    }
    
    fmt.Println(t)
}

链接:http://play.golang.org/p/sl0Cti5Mqw

以下代码也无法正常工作:

package main

import "fmt"
import "time"

func main() {
    t, err := time.Parse("201302031010", "201302031010")
    fmt.Println(t)

    if err != nil {
        panic(err)
    }
    
    fmt.Println(t)
}

链接:http://play.golang.org/p/OUmfNTdlce

英文:

Im attempting to learn go, its quite a fun language. Ive got a bunch of text files which we run imports across, the date is in the format YYYYMMDDHHmm. How do I get this to parse into an internal date format. The following doesn't work:

package main

import "fmt"
import "time"

func main() {
	t, err := time.Parse("YYYYMMDDHHmm", "201302031010")
	fmt.Println(t)

	if err != nil {
		panic(err)
	}
	
	fmt.Println(t)
}

http://play.golang.org/p/sl0Cti5Mqw

Neither does:

package main

import "fmt"
import "time"

func main() {
	t, err := time.Parse("201302031010", "201302031010")
	fmt.Println(t)

	if err != nil {
		panic(err)
	}
	
	fmt.Println(t)
}

http://play.golang.org/p/OUmfNTdlce

答案1

得分: 4

在Go语言中,时间格式的指定方式可能有点奇怪...你需要做的是展示如何在你的布局中显示"参考时间"(Mon Jan 2 15:04:05 -0700 MST 2006)。

所以对于你的格式,你需要的字符串是"200601021504"

package main

import "fmt"
import "time"

func main() {
    t, err := time.Parse("200601021504", "201302031010")
    fmt.Println(t)

    if err != nil {
        panic(err)
    }
    
    fmt.Println(t)
}

点击这里可以查看示例代码。

点击这里可以查看更多关于time.Parse的信息。

英文:

The way time formats are specified in Go can be a little strange... What you need to do is show how the "Reference Time" (Mon Jan 2 15:04:05 -0700 MST 2006) would be displayed in your layout.

So for your format, the string you need is "200601021504".

package main

import "fmt"
import "time"

func main() {
    t, err := time.Parse("200601021504", "201302031010")
    fmt.Println(t)

    if err != nil {
        panic(err)
    }
    
    fmt.Println(t)
}

http://play.golang.org/p/yKVh4gOOgP

http://golang.org/pkg/time/#Parse

huangapple
  • 本文由 发表于 2014年5月17日 09:00:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/23706586.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定