解析 Go 中无效字符串 “24-Sep.-20” 中的时间

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

Parsing time from unvalid string "24-Sep.-20" in Go

问题

我尝试使用各种方法解析这个字符串"24-Sep.-20",但是由于该字符串包含一个句点,所以仍然没有解决。

我想将我的日期转换为"24-09-2020"。

我该如何做到这一点?

英文:

I've try to parse this string "24-Sep.-20" use any method, but still not resolved because that string has a period.

I want convert my date to "24-09-2020".

How can I do this?

答案1

得分: 3

只需通过在(“-”)之前添加(“。”)来更新您的时间布局,然后将解析后的时间重新格式化为新的布局。

func main() {
	date := "24-Sep.-20"
	layout := "02-Jan.-06"
	t, _ := time.Parse(layout, date)

	newLayout := "02-01-2006"
	output := t.Format(newLayout)
	fmt.Println(output)
}

Playground: https://play.golang.org/p/AgR3DFRrK0q

英文:

Simply just by update your time layout by adding (.) before the (-), and then reformat your parsed time to the new layout.

func main() {
	date := "24-Sep.-20"
	layout := "02-Jan.-06"
	t, _ := time.Parse(layout, date)

	newLayout := "02-01-2006"
	output := t.Format(newLayout)
	fmt.Println(output)
}

Playground: https://play.golang.org/p/AgR3DFRrK0q

huangapple
  • 本文由 发表于 2021年10月4日 09:51:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/69430204.html
匿名

发表评论

匿名网友

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

确定