英文:
Need Help in conversion of time into seconds which can handle with hours and without hours in Golang
问题
想要将时间持续时间更改为秒,但不想每次都提供小时(小时是可选的)
package main
import (
"fmt"
)
func main() {
t1 := "01:30"
seconds, _ := ConvertTimeFormat(t1) // 对于这个不起作用
fmt.Println(seconds)
t2 := "01:01:15"
second, _ := ConvertTimeFormat(t2) // 对于这个起作用
fmt.Println(second)
}
func ConvertTimeFormat(st string) (int, error) {
var h, m, s int
n, err := fmt.Sscanf(st, "%d:%d:%d", &h, &m, &s)
fmt.Print(n, err)
if err != nil || n != 3 {
return 0, err
}
return h*3600 + m*60 + s, nil
}
希望这个翻译对你有帮助!
英文:
want to change time duration is seconds but don't want to give hours every time (hrs as optional)
package main
import (
"fmt"
)
func main() {
t1 := "01:30"
seconds, _ := ConvertTimeFormat(t1) // not working fine for this
fmt.Println(seconds)
t2 := "01:01:15"
second, _ := ConvertTimeFormat(t2) // working fine for this
fmt.Println(second)
}
func ConvertTimeFormat(st string) (int, error) {
var h, m, s int
n, err := fmt.Sscanf(st, "%d:%d:%d", &h, &m, &s)
fmt.Print(n, err)
if err != nil || n != 3 {
return 0, err
}
return h*3600 + m*60 + s, nil
}
答案1
得分: 1
你的代码有一个bug,因为你总是期望Scanf函数中有3个值。
尝试以另一种方式解析它,像这样:
package main
import (
"errors"
"fmt"
"strconv"
"strings"
)
func main() {
t1 := "01:30"
seconds, _ := ConvertTimeFormat(t1) // 对于这个例子无法正常工作
fmt.Println(seconds)
t2 := "01:01:15"
second, _ := ConvertTimeFormat(t2) // 对于这个例子可以正常工作
fmt.Println(second)
}
func ConvertTimeFormat(st string) (int, error) {
var sh, sm, ss string
parts := strings.Split(st, ":")
switch len(parts) {
case 2:
sm = parts[0]
ss = parts[1]
case 3:
sh = parts[0]
sm = parts[1]
ss = parts[2]
default:
return 0, errors.New("无效的格式")
}
var (
h, m, s int
err error
)
if sh != "" {
h, err = strconv.Atoi(sh)
if err != nil {
return 0, err
}
}
m, err = strconv.Atoi(sm)
if err != nil {
return 0, err
}
s, err = strconv.Atoi(ss)
if err != nil {
return 0, err
}
return h*3600 + m*60 + s, nil
}
另一个解决方案是处理错误并尝试以另一种格式解析:
func ConvertTimeFormat(st string) (int, error) {
var h, m, s int
_, err := fmt.Sscanf(st, "%d:%d:%d", &h, &m, &s)
fmt.Println(h, m, s, err)
if err != nil {
h, m, s = 0, 0, 0
_, err = fmt.Sscanf(st, "%d:%d", &m, &s)
if err != nil {
return 0, err
}
}
return h*3600 + m*60 + s, nil
}
英文:
Your code is buggy, since you always expect 3 values in the Scanf func.
Try to parse it another way, like:
package main
import (
"errors"
"fmt"
"strconv"
"strings"
)
func main() {
t1 := "01:30"
seconds, _ := ConvertTimeFormat(t1) // not working fine for this
fmt.Println(seconds)
t2 := "01:01:15"
second, _ := ConvertTimeFormat(t2) // working fine for this
fmt.Println(second)
}
func ConvertTimeFormat(st string) (int, error) {
var sh, sm, ss string
parts := strings.Split(st, ":")
switch len(parts) {
case 2:
sm = parts[0]
ss = parts[1]
case 3:
sh = parts[0]
sm = parts[1]
ss = parts[2]
default:
return 0, errors.New("Invalid format")
}
var (
h, m, s int
err error
)
if sh != "" {
h, err = strconv.Atoi(sh)
if err != nil {
return 0, err
}
}
m, err = strconv.Atoi(sm)
if err != nil {
return 0, err
}
s, err = strconv.Atoi(ss)
if err != nil {
return 0, err
}
return h*3600 + m*60 + s, nil
}
Another solution is to handle the error and try to parse it in the another format:
func ConvertTimeFormat(st string) (int, error) {
var h, m, s int
_, err := fmt.Sscanf(st, "%d:%d:%d", &h, &m, &s)
fmt.Println(h, m, s, err)
if err != nil {
h, m, s = 0, 0, 0
_, err = fmt.Sscanf(st, "%d:%d", &m, &s)
if err != nil {
return 0, err
}
}
return h*3600 + m*60 + s, nil
}
答案2
得分: 0
将输入字符串按照":"进行拆分,并进行反向迭代。
根据位置将字段乘以1、60或3600。
将结果加到秒数上。
代码
var mult = []int{1, 60, 60 * 60}
func ConvertTimeFormat(timeStr string) (int, error) {
var secs int
slice := strings.Split(timeStr, ":")
arrlen := len(slice)// 在这里检查长度是否小于等于3
for i := arrlen - 1; i >= 0; i-- {
elem, err := strconv.Atoi(slice[i])
if err != nil {
return -1, fmt.Errorf("在[%s]中解析[%s]时出错 [%v]",
timeStr, slice[i], err)
}
secs += (elem * mult[arrlen-i-1])
}
return secs, nil
}
错误的字符串 ""
, ":", ":20", "str:30, "::" 等将由 Atoi()
报告。
编辑:
也可以使用乘数而不是数组,这将增加额外的乘法操作。
func ConvertTimeFormat(timeStr string) (int, error) {
multiplier := 1
for i := arrlen - 1; i >= 0; i-- {
...
secs += (elem * multiplier)
multiplier *= 60
}
return secs, nil
}
英文:
Split input string at ":" and reverse iterate.
Multiply fields by 1, 60 or 3600 as per position
Add to seconds
Code
var mult = []int{1, 60, 60 * 60}
func ConvertTimeFormat(timeStr string) (int, error) {
var secs int
slice := strings.Split(timeStr, ":")
arrlen := len(slice)// Check length <=3 here
for i := arrlen - 1; i >= 0; i-- {
elem, err := strconv.Atoi(slice[i])
if err != nil {
return -1, fmt.Errorf("error parsing [%s] in [%s] [%v]",
slice[i], timeStr, err)
}
secs += (elem * mult[arrlen-i-1])
}
return secs, nil
}
Erroneous strings "", ":", ":20", "str:30, "::"
etc will be reported by Atoi()
Edit:
Could also use multiplier instead of array, would be extra multiplication operation.
func ConvertTimeFormat(timeStr string) (int, error) {
multiplier := 1
for i := arrlen - 1; i >= 0; i-- {
...
secs += (elem * multiplier)
multiplier *= 60
}
return secs, nil
}
答案3
得分: 0
也许更容易理解并自己重写,使用官方包time。
func main() {
t1 := "01:30"
backSeconds(t1)
t2 := "01:01:15"
backSeconds(t2)
// 输入: 01:30 ----处理: 01m30s ----结果: 90
// 输入: 01:01:15 ----处理: 01h01m15s ----结果: 3675
}
func backSeconds(str string) {
deal := preDeal(str)
parse, err := time.ParseDuration(deal)
if err != nil {
log.Println(err)
}
fmt.Println("输入: ", str, "----处理: ", deal, "----结果: ", parse.Seconds())
}
func preDeal(str string) string {
list := strings.Split(str, ":")
var build strings.Builder
tType := []string{"s", "m", "h"}
j := len(list) - 1
for i := 0; i < len(list); i++ {
build.WriteString(list[i] + tType[j-i])
}
return build.String()
}
英文:
maybe it's more easier to understand and rewrite by yourself. using official package time .
func main() {
t1 := "01:30"
backSeconds(t1)
t2 := "01:01:15"
backSeconds(t2)
// input: 01:30 ----deal: 01m30s ----result: 90
// input: 01:01:15 ----deal: 01h01m15s ----result: 3675
}
func backSeconds(str string) {
deal := preDeal(str)
parse, err := time.ParseDuration(deal)
if err != nil {
log.Println(err)
}
fmt.Println("input: ", str, "----deal: ", deal, "----result: ", parse.Seconds())
}
func preDeal(str string) string {
list := strings.Split(str, ":")
var build strings.Builder
tType := []string{"s", "m", "h"}
j := len(list) - 1
for i := 0; i < len(list); i++ {
build.WriteString(list[i] + tType[j-i])
}
return build.String()
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论