英文:
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 (
"fmt"
"time"
)
func main() {
value := "Thu, 05/19/11, 10:47PM"
// Writing down the way the standard time would look like formatted our way
layout := "Mon, 01/02/06, 03:04PM"
t, _ := time.Parse(layout, value)
fmt.Println(t)
}
// => "Thu May 19 22:47:00 +0000 2011"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论