将字符串日期(月份、年份)转换为time.Time类型。

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

Convert string date (Month, Year) to time.Time

问题

我有一个字符串:

  1. str := "Jan 2020"

我需要将其转换为Go语言中的time.time格式。请问我该如何做?

英文:

I have a string which is :

  1. str := "Jan 2020"

I need to convert this to time.time format in go.How can i do this please ?

答案1

得分: 2

你需要有一个布局字符串来指定如何解析你的字符串。例如:

  1. package main
  2. import (
  3. "time"
  4. "fmt"
  5. )
  6. func main() {
  7. time, err := time.Parse("Jan 2006", "Feb 2020")
  8. if err != nil {
  9. panic(err)
  10. }
  11. fmt.Println(time)
  12. }

你可以在这里找到更多关于标准布局的信息:这里

英文:

You need to have a layout string that specifies how to parse your string. For example:

<!-- language: go -->

  1. package main
  2. import (
  3. &quot;time&quot;
  4. &quot;fmt&quot;
  5. )
  6. func main() {
  7. time, err := time.Parse(&quot;Jan 2006&quot;, &quot;Feb 2020&quot;)
  8. if err != nil {
  9. panic(err)
  10. }
  11. fmt.Println(time)
  12. }

You may find more about the standard layouts here.

huangapple
  • 本文由 发表于 2017年6月17日 20:44:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/44604800.html
匿名

发表评论

匿名网友

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

确定