使用 Golang 的 time 包中的 ParseDuration 函数可以将时间字符串转换为 Duration 类型,然后使用 Seconds 方法将 Duration 类型转换为秒数。

以下是一个示例代码:

package main

import (
	"fmt"
	"time"
)

func main() {
	durationStr := '1m' // 要转换的时间字符串

	duration, err := time.ParseDuration(durationStr)
	if err != nil {
		fmt.Println("时间字符串格式不正确")
		return
	}

	seconds := int(duration.Seconds())
	fmt.Println(seconds) // 输出秒数
}

您可以将 durationStr 的值修改为 '1h' 或 '1d' 来测试不同的时间字符串。

Golang 时间字符串转换为秒数:解析 1m、1h、1d 等格式

原文地址: https://www.cveoy.top/t/topic/pgcI 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录