/
dtlib.go
76 lines (68 loc) · 1.96 KB
/
dtlib.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package cmd
// date-time library
// a group of functions related to time
import (
"fmt"
"github.com/araddon/dateparse"
"github.com/nleeper/goment"
"log"
"time"
)
// ConvertDate - convert a date to a different layout
func ConvertDate(t time.Time, layoutAny string) string {
layout, err := dateparse.ParseFormat(layoutAny)
if err != nil {
log.Fatalf("Error #80050: Can parse '%s'; %s\n", layoutAny, err)
}
return t.Format(layout)
}
// GetDuration - convert from allRootOptions.Amount, allRootOptions.Period
// to a time.Duration
func GetDuration(a int, period string) time.Duration {
duration := ""
if period == "hours" {
duration = "h"
} else if period == "minutes" {
duration = "m"
} else if period == "seconds" {
duration = "s"
} else if period == "days" {
duration="h"
a *= 24
} else {
log.Fatalf("Error #80620: unable to convert to time.Duration: '%d, %s'\n", a, period)
}
parsed, err := time.ParseDuration(fmt.Sprintf("%d%s", a, duration))
if err != nil {
log.Fatalf("Error #80625: unable to convert to time.Duration: '%d, %s'; %s\n", a, period, err)
}
return parsed
}
// GetDurationInSeconds - convert from allRootOptions.Amount, allRootOptions.Period to seconds
func GetDurationInSeconds(a int, period string) int {
duration := ""
if period == "hours" {
duration = "h"
} else if period == "minutes" {
duration = "m"
} else if period == "seconds" {
duration = "s"
} else if period == "days" {
duration="h"
a *= 24
} else {
log.Fatalf("Error #80620: unable to convert to time.Duration: '%d, %s'\n", a, period)
}
parsed, err := time.ParseDuration(fmt.Sprintf("%d%s", a, duration))
if err != nil {
log.Fatalf("Error #80625: unable to convert to time.Duration: '%d, %s'; %s\n", a, period, err)
}
return int(parsed.Seconds())
}
// GetTimeDifference - return the difference between to Goment objects
func GetTimeDifference(a, b goment.Goment) time.Duration {
aTime := a.ToTime()
bTime := b.ToTime()
d := bTime.Sub(aTime)
return d
}