如何将带有毫秒的字符串时间(hh:mm:ss.xxx)转换为 time.Time 类型?

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

How to convert a string time with milliseconds (hh:mm:ss.xxx) to time.Time?

问题

基本上,我有一个像这样的字符串时间:

15:56:36.113

我想将其转换为 time.Time 类型。

根据我所了解,使用 time.Parse() 时无法使用毫秒。

是否有其他方法可以将我的字符串转换为 time.Time 类型?

英文:

Basically I have times like this one as a string:

15:56:36.113

I want to convert it to time.Time.

From what I am reading I cannot use milliseconds when using time.Parse().

Is there another way to convert my string to time.Time ?

答案1

得分: 2

Package time

格式化参考时间

小数点后跟随一个或多个零表示小数秒,打印到指定的小数位数。小数点后跟随一个或多个九表示小数秒,打印到指定的小数位数,并去除尾部的零。在解析时,输入可以包含一个小数秒字段,即使布局不表示其存在。在这种情况下,小数点后跟随一系列数字将被解析为小数秒。

例如,

package main

import (
	"fmt"
	"time"
)

func main() {
	t, err := time.Parse("15:04:05", "15:56:36.113")
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(t)

	fmt.Println(t.Format("15:04:05.000"))

	h, m, s := t.Clock()
	ms := t.Nanosecond() / int(time.Millisecond)
	fmt.Printf("%02d:%02d:%02d.%03d\n", h, m, s, ms)
}

输出:

0000-01-01 15:56:36.113 +0000 UTC
15:56:36.113
15:56:36.113

注意:Time 类型的零值为 0000-01-01 00:00:00.000000000 UTC

英文:

> Package time
>
> Format Reference Time
>
> A decimal point followed by one or more zeros represents a fractional
> second, printed to the given number of decimal places. A decimal point
> followed by one or more nines represents a fractional second, printed
> to the given number of decimal places, with trailing zeros removed.
> When parsing (only), the input may contain a fractional second field
> immediately after the seconds field, even if the layout does not
> signify its presence. In that case a decimal point followed by a
> maximal series of digits is parsed as a fractional second.

For example,

package main

import (
	"fmt"
	"time"
)

func main() {
	t, err := time.Parse("15:04:05", "15:56:36.113")
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(t)

	fmt.Println(t.Format("15:04:05.000"))

	h, m, s := t.Clock()
	ms := t.Nanosecond() / int(time.Millisecond)
	fmt.Printf("%02d:%02d:%02d.%03d\n", h, m, s, ms)
}

Output:

0000-01-01 15:56:36.113 +0000 UTC
15:56:36.113
15:56:36.113

Note: The zero value of type Time is 0000-01-01 00:00:00.000000000 UTC.

答案2

得分: 1

package main

import (
	"fmt"
	"time"
)

func main() {
	s := "15:56:36.113"
	t, _ := time.Parse("15:04:05.000", s)

	fmt.Print(t)
}

输出:

0000-01-01 15:56:36.113 +0000 UTC

你可以在这里进行更多的尝试:https://play.golang.org/p/3A3e8zHQ8r

英文:
package main

import (
	"fmt"
	"time"
)

func main() {
	s := "15:56:36.113"
	t,_ := time.Parse("15:04:05.000", s)

	fmt.Print(t)
}

Output:

0000-01-01 15:56:36.113 +0000 UTC

You can play with it more here: https://play.golang.org/p/3A3e8zHQ8r

huangapple
  • 本文由 发表于 2017年9月6日 16:00:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/46069792.html
匿名

发表评论

匿名网友

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

确定