Skip to content

Commit 73d13c2

Browse files
committed
Format nil time.Time's without panicking
Fixes #82 Updates the DateFormat function to return an empty string if the provided `*time.Time` is `nil`, instead of panicking.
1 parent 98f2ecb commit 73d13c2

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

app/utils/date.go

+4
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,10 @@ var conversion = map[rune]string{
5656
// %z numbers representing the timezone, ex: "-0700"
5757
// %L milliseconds, ex: ".000"
5858
func DateFormat(t *time.Time, format string) string {
59+
if t == nil {
60+
return ""
61+
}
62+
5963
retval := make([]byte, 0, len(format))
6064
for i, ni := 0, 0; i < len(format); i = ni + 2 {
6165
ni = strings.IndexByte(format[i:], '%')

app/utils/date_test.go

+9-1
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,10 @@ package utils
22

33
import (
44
"fmt"
5-
. "github.com/smartystreets/goconvey/convey"
65
"testing"
76
"time"
7+
8+
. "github.com/smartystreets/goconvey/convey"
89
)
910

1011
func ExampleDateFormat() {
@@ -22,4 +23,11 @@ func TestDateFormat(t *testing.T) {
2223
So(dateFmt, ShouldEqual, "2009-11-10 23:00")
2324
})
2425
})
26+
27+
Convey("It should not panic when trying to format nil dates", t, func() {
28+
dateFmt := DateFormat(nil, "%Y-%m-%d %H:%M")
29+
Convey("Test DateFormat", func() {
30+
So(dateFmt, ShouldEqual, "")
31+
})
32+
})
2533
}

0 commit comments

Comments
 (0)