golang 把 剩余时分秒 "01:43:00" 转换成剩余 秒数
时间: 2023-07-22 12:07:28 浏览: 59
可以使用 time 包来进行时间的解析和计算。在 Golang 中,可以使用 time.ParseDuration() 函数将时间字符串解析为 duration 类型,然后使用 duration.Seconds() 函数获取总秒数。下面是一个示例代码:
```go
package main
import (
"fmt"
"time"
)
func main() {
durationStr := "01:43:00"
duration, err := time.ParseDuration(durationStr)
if err != nil {
fmt.Println("解析时间失败:", err)
return
}
seconds := duration.Seconds()
fmt.Printf("%s 转换成剩余秒数: %.0f\n", durationStr, seconds)
}
```
输出结果为:
```
01:43:00 转换成剩余秒数: 6180
```
注意:time.ParseDuration() 函数接受的时间字符串必须符合特定的格式,即 "小时:分钟:秒",例如 "01:43:00"。如果时间字符串的格式不正确,将会返回解析错误。
相关问题
golang 毫秒数转成 HH:MM:SS.mmm 时间格式
在 Go 中,你可以使用`time`包来处理时间和日期。要将毫秒数转换为HH:MM:SS.mmm的时间格式,你可以使用以下代码:
```go
package main
import (
"fmt"
"time"
)
func MillisecondsToTime(milliseconds int64) string {
seconds := milliseconds / 1000
milliseconds = milliseconds % 1000
hours := seconds / 3600
seconds = seconds % 3600
minutes := seconds / 60
seconds = seconds % 60
return fmt.Sprintf("%02d:%02d:%02d.%03d", hours, minutes, seconds, milliseconds)
}
func main() {
milliseconds := int64(1234567)
timeFormatted := MillisecondsToTime(milliseconds)
fmt.Println(timeFormatted)
}
```
在上面的代码中,`MillisecondsToTime`函数将毫秒数转换为小时(hours)、分钟(minutes)、秒(seconds)和毫秒(milliseconds)的格式。然后,使用`fmt.Sprintf`将这些值格式化为HH:MM:SS.mmm的字符串。
运行上面的代码将输出:
```
00:20:34.567
```
你可以将`milliseconds`变量替换为你想要转换的实际毫秒数。
golang将字符串“Jun 11 11:01:01”,转换成时间类型
可以使用golang的time包中的Parse函数来将字符串转换成时间类型。示例代码如下:
```go
package main
import (
"fmt"
"time"
)
func main() {
str := "Jun 11 11:01:01"
layout := "Jan 2 15:04:05"
t, err := time.Parse(layout, str)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(t)
}
}
```
解释一下:
- `str` 是要转换的字符串。
- `layout` 是字符串的时间格式,`Jan` 表示月份,`2` 表示月中的第几天,`15` 表示小时,`04` 表示分钟,`05` 表示秒。
- `time.Parse(layout, str)` 将字符串转换成时间类型,如果出现错误,则返回错误信息。
运行结果为:
```
2021-06-11 11:01:01 +0000 UTC
```