将UTC TZ时间转换为Golang中的YYYY-MM-DD HH:MM:SS.zzzzzzz格式。

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

Convert UTC TZ Time to YYYY-MM-DD HH:MM:SS.zzzzzzz in Golang

问题

我想将一个日期字符串(例如"2022-11-08T15:27:41.01333333Z")转换为"2022-11-08 15:27:41.01333333"的格式。我希望将UTC日期转换为可读的SQL Server datetime2表达式。

package main

import (
    "fmt"
    "time"
)

func main() {
    t := "2022-11-08T15:27:41.01333333Z"
    // 如何解析?
}

你需要使用time.Parse函数来解析日期字符串。在这种情况下,你可以使用time.RFC3339作为解析日期字符串的格式。以下是修改后的代码:

package main

import (
    "fmt"
    "time"
)

func main() {
    t := "2022-11-08T15:27:41.01333333Z"
    parsedTime, err := time.Parse(time.RFC3339, t)
    if err != nil {
        fmt.Println("解析日期字符串时出错:", err)
        return
    }
    formattedTime := parsedTime.Format("2006-01-02 15:04:05.99999999")
    fmt.Println(formattedTime)
}

这将输出:2022-11-08 15:27:41.01333333,这是你想要的格式化日期字符串。

英文:

I'd like to take an example date string such as "2022-11-08T15:27:41.01333333Z" and convert it to "2022-11-08 15:27:41.01333333" in Golang. I essentially just want to turn the UTC date into a readable datetime2 expression for SQL Server.

package main

import (
    "fmt"
    "time"
)

func main () {
    t := "2022-11-08T15:27:41.01333333Z"
    // How to Parse?
}

答案1

得分: 1

这应该可以工作:

package main

import (
	"fmt"
	"time"
)

func main() {
	t := "2022-11-08T15:27:41.01333333Z"
	const layout = "2006-01-02T15:04:05.00000000Z07:00"
	x, err := time.Parse(layout, t)
	const render = "2006-01-02 15:04:05.00000000"
	fmt.Println(x.Format(render), err)
}
英文:

This should work:

package main

import (
	"fmt"
	"time"
)

func main() {
	t := "2022-11-08T15:27:41.01333333Z"
	const layout = "2006-01-02T15:04:05.00000000Z07:00"
	x, err := time.Parse(layout, t)
	const render = "2006-01-02 15:04:05.00000000"
	fmt.Println(x.Format(render), err)
}

huangapple
  • 本文由 发表于 2022年11月18日 22:50:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/74491467.html
匿名

发表评论

匿名网友

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

确定