将字符串转换为时间或创建一个时间常量

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

Convert string to time or create a time constant

问题

这可能是一个愚蠢的问题,但我似乎找不到如何将字符串格式的日期转换为日期时间格式的方法。非常感谢!

s := "12-25-2012"
var t time.Time

t = s.Time() ??? 

我希望t包含s的值。

英文:

This is maybe a stupid question to ask but I can't seem to find how to convert date in string format to date time format. Many thanks!

s := "12-25-2012"
var t time.Time

t = s.Time() ??? 

I would like t to contain the value of s.

答案1

得分: 4

你需要使用time.Parse()和与你提供的日期字符串匹配的格式字符串。

这是一个使用你的日期格式的示例。

package main

import (
    "fmt"
    "time"
)

func main() {
    s := "12-25-2012"
    format_string := "01-02-2006"
    t, err := time.Parse(format_string, s)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%v\n", t)
}

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

你可以在这篇帖子中了解更多关于制作自定义格式字符串的内容。

英文:

You need time.Parse() and a format string that matches your supplied date string.

Here's an example using your date format.

package main

import (
	"fmt"
	"time"
	)

func main() {
	s := "12-25-2012"
	format_string := "01-02-2006"
	t, err := time.Parse(format_string, s)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%v\n", t)
}

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

You can read more about making custom format strings in <a href="https://stackoverflow.com/questions/14106541/go-parsing-date-time-strings-which-are-not-standard-formats/14106561#14106561">this post</a>.

答案2

得分: 2

根据这篇文章:

package main

import (
    "fmt"
    "time"
)

func main() {
    value  := "Thu, 05/19/11, 10:47PM"
    // 将标准时间按照我们的格式写下来
    layout := "Mon, 01/02/06, 03:04PM"
    t, _ := time.Parse(layout, value)
    fmt.Println(t)
}

// => "Thu May 19 22:47:00 +0000 2011"
英文:

According to this article:

package main

import (
    &quot;fmt&quot;
    &quot;time&quot;
)

func main() {
    value  := &quot;Thu, 05/19/11, 10:47PM&quot;
    // Writing down the way the standard time would look like formatted our way
    layout := &quot;Mon, 01/02/06, 03:04PM&quot;
    t, _ := time.Parse(layout, value)
    fmt.Println(t)
}

// =&gt; &quot;Thu May 19 22:47:00 +0000 2011&quot;

huangapple
  • 本文由 发表于 2013年1月21日 02:34:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/14427830.html
匿名

发表评论

匿名网友

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

确定