-
Notifications
You must be signed in to change notification settings - Fork 1
/
sqltime.go
59 lines (50 loc) · 1.52 KB
/
sqltime.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
// sqltime
// defines a new type `sqltime.Time` that address the issue of the database timestamp having a different
// precision then golang time.Time
// particularly useful for testing
//
// ATTENTION : this type will truncate the value of time.Time resulting in a data loss of magniture of the value
// of TruncateOff
package sqltime
import (
"database/sql/driver"
"fmt"
"time"
)
// the degree of precision to REMOVE
// Default time.Microsecond
var TruncateOff = time.Microsecond
// Local the timezone the database is set to
// default UTC
var DatabaseLocation, _ = time.LoadLocation("UTC")
// Time
// type that can be used with sql driver's and offers
// a less precise sql timestamp
type Time struct {
time.Time
}
// satisfy the sql.scanner interface
func (t *Time) Scan(value interface{}) error {
rt, ok := value.(time.Time)
if !ok {
return fmt.Errorf("dbtime could not convert value into time.Time. value: %v", value)
}
*t = Time{format(rt)}
return nil
}
// satifies the driver.Value interface
func (t Time) Value() (driver.Value, error) {
return format(t.Time), nil //format just in case
}
// Now wrapper around the time.Now() function
func Now() Time {
return Time{format(time.Now())}
}
// Date wrapper around the time.Date() function
func Date(year int, month time.Month, day, hour, min, sec, nsec int, loc *time.Location) Time {
return Time{format(time.Date(year, month, day, hour, min, sec, nsec, loc))}
}
// insure the correct format
func format(t time.Time) time.Time {
return t.In(DatabaseLocation).Truncate(TruncateOff)
}