-
Notifications
You must be signed in to change notification settings - Fork 1
/
time-to-db.go
70 lines (59 loc) · 2.2 KB
/
time-to-db.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
/*
© 2022–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)
ISC License
*/
package sqliter
import (
"database/sql"
"time"
"github.com/haraldrudell/parl/perrors"
"github.com/haraldrudell/parl/ptime"
)
const (
nsUTCLength = len("2006-01-02T15:04:05.000000000Z")
)
// TimeToDB converts ns-resolution Go time.Time in any time.Location to
// SQLite TEXT ISO8601 nano-second resolution UTC time zone
// - SQLite TEXT: “2022-01-01T08:00:00.000000000Z”
func TimeToDB(t time.Time) (dbValue string) {
return ptime.Rfc3339nsz(t) // “2022-01-01T08:00:00.000000000Z”
}
// ToTime parses SQLite TEXT to Go time.Time in Local location
// - SQLite TEXT ISO8601 nano-second resolution UTC time zone
// - SQLite TEXT: “2022-01-01T08:00:00.000000000Z”
func ToTime(timeString string) (t time.Time, err error) {
// check length “2006-01-02T15:04:05.000000000Z”
if len(timeString) != nsUTCLength {
err = perrors.ErrorfPF("bad length: %d exp %d", len(timeString), nsUTCLength)
return // bad length: t: zero value err: non-nil
}
// parse “2006-01-02T15:04:05.000000000Z”
if t, err = ptime.ParseRfc3339nsz(timeString); err != nil {
err = perrors.ErrorfPF("time.Parse: %w", err)
return // bad parse: t: zero-value err: non-nil
}
t = t.Local()
return // good return: t: time in Local, err: nil
}
// TimeToDBNullable converts ns-resolution Go time.Time in any time.Location to
// SQLite TEXT ISO8601 nano-second resolution UTC time zone
// - for nullable database column
// - SQLite TEXT: “2022-01-01T08:00:00.000000000Z”
// - NULL corresponds to time.Time{} [time.Time.IsZero] true
func TimeToDBNullable(t time.Time) (dbValue any) {
if t.IsZero() {
return nil // empty string
}
return ptime.Rfc3339nsz(t)
}
// NullableToTime parses SQLite TEXT to Go time.Time in Local location
// - nullable database column
// - SQLite TEXT ISO8601 nano-second resolution UTC time zone
// - SQLite TEXT: “2022-01-01T08:00:00.000000000Z”
// - NULL corresponds to time.Time{} [time.Time.IsZero] true
func NullableToTime(nullString sql.NullString) (t time.Time, err error) {
if !nullString.Valid {
return // NULL: t.IsZero()
}
return ToTime(nullString.String)
}