forked from RichardKnop/go-oauth2-server
/
time.go
56 lines (50 loc) · 1.37 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
package util
import (
"time"
)
// https://golang.org/pkg/time/#pkg-constants
const (
// RFC3339Mili is a modification of RFC3339Nano to only include ms (3 decimal places)
RFC3339Mili = "2006-01-02T15:04:05.999Z07:00"
// DateFormat used for things such as date of birth (when time does not matter)
DateFormat = "2006-01-02"
)
// FormatTime formats a time object to RFC3339 with ms precision
func FormatTime(timestamp *time.Time) string {
if timestamp == nil {
return ""
}
return timestamp.UTC().Format(RFC3339Mili)
}
// ParseTimestamp parses a string representation of a timestamp in RFC3339
// format and returns a time.Time instance
func ParseTimestamp(timestamp string) (*time.Time, error) {
// RFC3339 = "2006-01-02T15:04:05Z07:00"
if timestamp == "" {
return nil, nil
}
t, err := time.Parse(time.RFC3339, timestamp)
if err != nil {
return nil, err
}
return &t, nil
}
// FormatDate formats a time object to a date only format, e.g. 2006-01-02
func FormatDate(timestamp *time.Time) string {
if timestamp == nil {
return ""
}
return timestamp.UTC().Format(DateFormat)
}
// ParseDate parses a string representation of a date format
// and returns a time.Time instance
func ParseDate(timestamp string) (*time.Time, error) {
if timestamp == "" {
return nil, nil
}
t, err := time.Parse(DateFormat, timestamp)
if err != nil {
return nil, err
}
return &t, nil
}