golang实现计算时间差工具

帮同事写了一个简单的小脚本,用go语言实现,输入两个时间,可以计算这两个时间的差值。

代码比较冗余,但也实现了基本功能.

比如你要计算15:46和23:21之间的时间差值,你应该按照此格式输入:15:46 23:21

至于单位,小时:分钟分钟:秒钟 的输入都是可以用的,因为都是60进制

Talk is cheap, then show you the code
package main

import (
    "fmt"
    "strconv"
    "strings"
)

func main() {
  
  //time_minute1,time_second1
    var tm1, tm2, ts1, ts2 int

    welcome()
    for {

        var a string
        fmt.Scanf("%s", &a)

    //strings.FieldsFunc 根据指定符号分割字符串为数组
        sa := strings.FieldsFunc(a, func(s rune) bool {
            if s == ':' {
                return true
            }
            return false
        })
        res := arrToStr(sa)
        num, _ := strconv.Atoi(res)
        tm1, ts1, tm2, ts2 = getEveryone(num)
        getETime(tm1, ts1, tm2, ts2)

    }

}

func welcome() {
    fmt.Println("***********************************")
    fmt.Println("***********输入后计算结果************")
}

//将字符串数字拼接成字符串
func arrToStr(arr []string) string {
    var result string
    for _, v := range arr {
        result += v
    }
    return result
}

//得到每一位的值
func getEveryone(n int) (tm1, ts1, tm2, ts2 int) {

    // fmt.Println(n)
    tm1 = n / 1e6
    ts1 = n / 1e4 % 1e2
    tm2 = n / 1e2 % 1e2
    ts2 = n % 1e2
    return tm1, ts1, tm2, ts2
}

func getETime(tm1, ts1, tm2, ts2 int) {
    if (ts2 - ts1) < 0 {
        ts2 = ts2 - ts1 + 60
        tm2 = tm2 - tm1 - 1
    } else {
        ts2 = ts2 - ts1
        tm2 = tm2 - tm1
    }
    fmt.Printf("        *时间差为%d:%d\n", tm2, ts2)
    fmt.Println("---------------------------")
}