Golang时间转中文描述(如秒转分,输入70秒输出1分10秒)
package main
import (
"fmt"
"strings"
)
func formatDuration(seconds int) string {
if seconds == 0 {
return "0秒"
}
var parts []string
units := []struct {
seconds int
name string
}{
{31536000, "年"},
{86400, "天"},
{3600, "时"},
{60, "分"},
{1, "秒"},
}
for _, unit := range units {
if seconds >= unit.seconds {
value := seconds / unit.seconds
remainder := seconds % unit.seconds
parts = append(parts, fmt.Sprintf("%d%s", value, unit.name))
seconds = remainder
}
}
return strings.Join(parts, "")
}
func main() {
fmt.Println(formatDuration(70)) // 输出:1分10秒
fmt.Println(formatDuration(31536000)) // 输出:1年
fmt.Println(formatDuration(0)) // 输出:0秒
fmt.Println(formatDuration(31536600)) // 输出:1年10分
fmt.Println(formatDuration(3661)) // 输出:1时1分1秒
}
不断学习,做更好的自己!

浙公网安备 33010602011771号