将一个MySQL的日期时间字符串转换为time.Time格式。

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

Convert a MySQL datetime string to time.Time format

问题

我只能帮你翻译文本内容,以下是翻译好的结果:

我无法将一个 SQL datetime(MySQL)值解析为 time.Time 值。我找不到适合 SQL datetime 的布局,并且对此如何工作也不太理解。

我想我不是第一个遇到这个问题的人,尽管我真的找不到应该如何解决这个问题。

输入:

2015-12-23 00:00:00

期望的输出:

1450825200

代码:

time, err := time.Parse(time.SomeSqlDateTimeLayout, "2015-12-23 00:00:00")
timestamp := time.Unix()
英文:

I just cant manage to parse an SQL datetime (MySQL) value into a time.Time value. I cant find the layout fitting sql datetime. And also not really understand how this works.

I do imagine I'am not the first struggling with this, though i cant really find how I should make this work.

Input:

2015-12-23 00:00:00

Desired output:

1450825200

Code

time, err := time.Parse(time.SomeSqlDateTimeLayout, "2015-12-23 00:00:00")
timestamp := time.Unix()

答案1

得分: 14

你可以为解析创建自己的时间格式,如果标准库中不存在的话。

package main

import (
	"fmt"
	"time"
)

func main() {
	layout := "2006-01-02 15:04:05"
	str := "2015-12-23 00:00:00"
	t, err := time.Parse(layout, str)

	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(t.Unix())
}

输出结果为:

1450828800

我不知道官方的时间格式文档在哪里,但你可以在这里找到,从第64行开始。

英文:

You can create your own time format for parsing, if one does not exist in standard library.

package main

import (
	"fmt"
	"time"
)

func main() {
	layout := "2006-01-02 15:04:05"
	str := "2015-12-23 00:00:00"
	t, err := time.Parse(layout, str)

	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(t.Unix())
}

Output

1450828800

I do not know were official documentation for time format is, but you can find it here, from line 64.

答案2

得分: 2

确实,我不知道Go标准库中是否有支持ISO-8601解析的功能。

让我们使用最接近的RFC-3309:

package main

import (
  "fmt"
  "time"
  "strings"
)

func main() {

  // 将ISO-8601转换为RFC-3339格式
  rfc3339t := strings.Replace("2015-12-23 00:00:00", " ", "T", 1) + "Z"

  // 解析RFC-3339日期时间
  t, err := time.Parse(time.RFC3339, rfc3339t)
  if err != nil {
    panic(err)
  }

  // 转换为Unix时间
  ut := t.UnixNano() / int64(time.Millisecond)

  fmt.Println(ut)
}

输出结果为:

1450828800000

希望对你有所帮助!

英文:

Indeed, I'm not aware of any ISO-8601 parsing support in Go's standard libraries.

Let us use RFC-3309, which is the closest:

package main

import (
  "fmt"
  "time"
  "strings"
)

func main() {

  // convert iso-8601 into rfc-3339 format
  rfc3339t := strings.Replace("2015-12-23 00:00:00", " ", "T", 1) + "Z"

  // parse rfc-3339 datetime
  t, err := time.Parse(time.RFC3339, rfc3339t)
  if err != nil {
 	panic(err)
  }

  // convert into unix time
  ut := t.UnixNano() / int64(time.Millisecond)

  fmt.Println(ut)
}

Output

1450828800000

Playground: http://play.golang.org/p/HxZCpxmjvg

Hope this helps!

huangapple
  • 本文由 发表于 2015年12月23日 23:01:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/34438395.html
匿名

发表评论

匿名网友

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

确定