基本上,您想要:
- 将所有内容转换为秒
- 除以 2
- 转换回时:分:秒
(并对ffmpeg 进行一些格式化)。
另请注意,此答案可以概括为除以n,而不仅仅是减半。
import (
"fmt"
"strconv"
"strings"
)
// ffmpeg uses the format HOURS:MM:SS.MICROSECONDS
func getDividedTime(time string, n int) string {
times := strings.Split(time, ":")
// get rid of microseconds
times[2] = strings.Split(times[2], ".")[0]
// conversions
minutesToSeconds := 60
hoursToSeconds := 60 * minutesToSeconds
// convert everything to seconds
seconds, _ := strconv.Atoi(times[2])
minutes, _ := strconv.Atoi(times[1])
hours, _ := strconv.Atoi(times[0])
secMinutes := minutes * minutesToSeconds
secHours := hours * hoursToSeconds
totalSeconds := seconds + secHours + secMinutes
totalSeconds /= n
// update time and grab seconds
newSeconds := totalSeconds % 60
totalSeconds /= 60
// update time and grab minutes
newMinutes := totalSeconds % 60
totalSeconds /= 60
newHours := totalSeconds % 3600
times[0] = strconv.Itoa(newHours)
times[1] = strconv.Itoa(newMinutes)
times[2] = strconv.Itoa(newSeconds)
// zero padding for seconds and minutes (not hours)
if newMinutes < 10 {
times[1] = "0" + times[1]
}
if newSeconds < 10 {
times[2] = "0" + times[2]
}
dividedTime := strings.Join(times[:], ":")
return dividedTime
}
func main() {
// create some tests
tables := []struct {
inputTime string
correctTime string
}{
{"0:11:28.956000", "0:05:44"},
{"1:00:00.111999", "0:30:00"},
{"1:15:00.111999", "0:37:30"},
{"1:45:00.111999", "0:52:30"},
{"0:59:00.000000", "0:29:30"},
{"2:04:22.123151", "1:02:11"},
{"0:00:00.000000", "0:00:00"},
{"0:00:03.000000", "0:00:01"},
{"0:00:04.000000", "0:00:02"},
{"0:20:00.000000", "0:10:00"},
{"0:02:00.000000", "0:01:00"},
{"99:00:00.000000", "49:30:00"},
}
// ensure output matches truth values
for _, table := range tables {
output := getDividedTime(table.inputTime, 2) // cut time in half
if output != table.correctTime {
fmt.Printf("failure: expected: %s, got: %s\n", table.correctTime, output)
}
}
}