Golang:从日期时间字符串中提取时间

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

Golang: extract time from datetime string

问题

我正在尝试从一个golang的日期时间字符串中提取时间,以下是我的代码:

  1. func GetTimeStr(d string) string {
  2. layout := "2014-09-12T11:45:26"
  3. d = d[:len(layout)]
  4. t, _ := time.Parse(layout, d)
  5. return t.Format("15:04:05")
  6. }

我的输入看起来像这样:

  1. 2022-09-23T16:28:19.846821Z

然而,我得到的结果是 00:00:00,我做错了什么?

英文:

I am trying to extract the time from a datetime string in golang, here is what I have:

  1. func GetTimeStr(d string) string {
  2. layout := "2014-09-12T11:45:26"
  3. d = d[:len(layout)]
  4. t, _ := time.Parse(layout, d)
  5. return t.Format("15:04:05")
  6. }

My input look like this:

  1. 2022-09-23T16:28:19.846821Z

However I am getting 00:00:00, what am I doing wrong?

答案1

得分: 2

你的布局字符串是错误的。尝试进行更改:

  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func main() {
  7. fmt.Println(GetTimeStr("2022-09-23T16:28:19.846821Z"))
  8. }
  9. func GetTimeStr(d string) string {
  10. layout := "2006-01-02T15:04:05"
  11. d = d[:len(layout)]
  12. t, _ := time.Parse(layout, d)
  13. return t.Format("15:04:05")
  14. }

这段代码的作用是将给定的时间字符串转换为指定格式的时间字符串。

英文:

Your layout string is wrong. Try changing it:

  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func main() {
  7. fmt.Println(GetTimeStr("2022-09-23T16:28:19.846821Z"))
  8. }
  9. func GetTimeStr(d string) string {
  10. layout := "2006-01-02T15:04:05"
  11. d = d[:len(layout)]
  12. t, _ := time.Parse(layout, d)
  13. return t.Format("15:04:05")
  14. }

huangapple
  • 本文由 发表于 2022年9月24日 00:31:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/73830647.html
匿名

发表评论

匿名网友

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

确定