change string type to date in golang

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

change string type to date in golang

问题

我正在为服务器获取一个类型为字符串的输入 Wed 2022-08-10 09:08:53 UTC。我需要检查服务器已经运行了多长时间。
我试图将这个字符串解析为日期,然后从当前时间中减去它,以获取以分钟为单位的运行时间。
在使用 time.Parse() 解析字符串时,我遇到了错误。我认为我的日期格式可能有问题。

英文:

I am getting an input of type string Wed 2022-08-10 09:08:53 UTC for a server .I need to check for how long the server is up and running.
I am trying to parse this string to date and then subtract it from current time to get the uptime in minutes.
I am getting error in parsing the string while using time.Parse(). I am thinking there is some issue with my layout.

答案1

得分: 3

你的格式似乎有些独特,我在time包中找不到预定义的常量来表示它。但是你可以构建自己的格式字符串。

package main

import (
	"fmt"
	"time"
)

func main(){
	t, err := time.Parse("Mon 2006-01-02 15:04:05 MST", "Wed 2022-08-10 09:08:53 UTC")

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

	fmt.Printf("距离现在的时间:%v", time.Since(t))
}

希望对你有帮助!

英文:

Your format seems a bit unique and I could not find predefined constant for it in time package. But you could construct your own format string

package main

import (
	"fmt"
	"time"
)

func main(){
	t, err := time.Parse("Mon 2006-01-02 15:04:05 MST", "Wed 2022-08-10 09:08:53 UTC")

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

	fmt.Printf("time since: %v", time.Since(t))
}

huangapple
  • 本文由 发表于 2022年8月11日 14:52:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/73316423.html
匿名

发表评论

匿名网友

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

确定