forked from martinlindhe/subtitles
-
Notifications
You must be signed in to change notification settings - Fork 0
/
time.go
60 lines (52 loc) · 1.27 KB
/
time.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package subtitles
import (
"fmt"
"math"
"regexp"
"strconv"
"strings"
"time"
)
// makeTime is a helper to create a time duration
func makeTime(h int, m int, s int, ms int) time.Time {
return time.Date(0, 1, 1, h, m, s, ms*1000*1000, time.UTC)
}
// parseTime parses a subtitle time (duration since start of film)
func parseTime(in string) (time.Time, error) {
// . and , to :
in = strings.Replace(in, ",", ":", -1)
in = strings.Replace(in, ".", ":", -1)
if strings.Count(in, ":") == 1 {
in = "00:" + in
}
if strings.Count(in, ":") == 2 {
in += ":000"
}
r1 := regexp.MustCompile("([0-9]+):([0-9]+):([0-9]+):([0-9]+)")
matches := r1.FindStringSubmatch(in)
if len(matches) < 5 {
return time.Now(), fmt.Errorf("[srt] Regexp didnt match: %s", in)
}
h, err := strconv.Atoi(matches[1])
if err != nil {
return time.Now(), err
}
m, err := strconv.Atoi(matches[2])
if err != nil {
return time.Now(), err
}
s, err := strconv.Atoi(matches[3])
if err != nil {
return time.Now(), err
}
ms, err := strconv.Atoi(matches[4])
if err != nil {
return time.Now(), err
}
return makeTime(h, m, s, ms), nil
}
func secondsToTime(s float64) time.Time {
zero := makeTime(0, 0, 0, 00)
s = math.Round(s*1000) / 1000
return zero.Add(time.Duration(s * float64(time.Second)))
}