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

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

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

问题

我有一个字符串:

str := "Jan 2020"

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

英文:

I have a string which is :

str := "Jan 2020"

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

答案1

得分: 2

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

package main

import (
	"time"
	"fmt"
)

func main() {
	time, err := time.Parse("Jan 2006", "Feb 2020")
	if err != nil {
		panic(err)
	}
	fmt.Println(time)
}

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

英文:

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

<!-- language: go -->

package main

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

func main() {
	time, err := time.Parse(&quot;Jan 2006&quot;, &quot;Feb 2020&quot;)
	if err != nil {
		panic(err)
	}
	fmt.Println(time)
}

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:

确定