/
date_time.go
90 lines (72 loc) · 2.4 KB
/
date_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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package domain
import (
"errors"
"fmt"
"time"
"flamingo.me/flamingo/v3/framework/flamingo"
)
// DateTimeFormatter has a couple of helpful methods to format date and times
type DateTimeFormatter struct {
logger flamingo.Logger
DateFormat string
TimeFormat string
DateTimeFormat string
localDateTime time.Time
dateTime time.Time
}
// ErrInvalidLocation represents invalid location, i.e. time zone error
const ErrInvalidLocation = "datetimeformatter.invalidlocation"
// SetDateTime setter for private member
func (dtf *DateTimeFormatter) SetDateTime(time time.Time, localtime time.Time) {
dtf.dateTime = time
dtf.localDateTime = localtime
}
// SetLocation sets location for local time
func (dtf *DateTimeFormatter) SetLocation(loc string) error {
location, err := time.LoadLocation(loc)
if err != nil {
dtf.logger.WithField(flamingo.LogKeyMethod, "SetLocation").Error(
fmt.Sprintf("%s: failed to get the given location: %v", loc, err),
)
return errors.New(ErrInvalidLocation)
}
dtf.localDateTime = dtf.dateTime.In(location)
return nil
}
// SetLogger sets the logger instance
func (dtf *DateTimeFormatter) SetLogger(logger flamingo.Logger) {
dtf.logger = logger
dtf.logger.WithField(flamingo.LogKeyCategory, "DateTimeFormatter")
}
// Format datetime
func (dtf *DateTimeFormatter) Format(format string) string {
return dtf.dateTime.Format(format)
}
// FormatLocale formats the local time
func (dtf *DateTimeFormatter) FormatLocale(format string) string {
return dtf.localDateTime.Format(format)
}
// FormatDate formats the date
func (dtf *DateTimeFormatter) FormatDate() string {
return dtf.dateTime.Format(dtf.DateFormat)
}
// FormatTime formats the time
func (dtf *DateTimeFormatter) FormatTime() string {
return dtf.dateTime.Format(dtf.TimeFormat)
}
// FormatDateTime formats both date and time
func (dtf *DateTimeFormatter) FormatDateTime() string {
return dtf.dateTime.Format(dtf.DateTimeFormat)
}
// FormatToLocalDate formats for local date
func (dtf *DateTimeFormatter) FormatToLocalDate() string {
return dtf.localDateTime.Format(dtf.DateFormat)
}
// FormatToLocalTime formats the local time
func (dtf *DateTimeFormatter) FormatToLocalTime() string {
return dtf.localDateTime.Format(dtf.TimeFormat)
}
// FormatToLocalDateTime formats both locale date and time
func (dtf *DateTimeFormatter) FormatToLocalDateTime() string {
return dtf.localDateTime.Format(dtf.DateTimeFormat)
}