diff --git a/text/transformer.go b/text/transformer.go index 5056358..d01c0eb 100644 --- a/text/transformer.go +++ b/text/transformer.go @@ -22,6 +22,15 @@ var ( colorsNumberNegative = Colors{FgHiRed} colorsNumberZero = Colors{} colorsURL = Colors{Underline, FgBlue} + rfc3339Milli = "2006-01-02T15:04:05.000Z07:00" + rfc3339Micro = "2006-01-02T15:04:05.000000Z07:00" + + possibleTimeLayouts = []string{ + time.RFC3339, + rfc3339Milli, // strfmt.DateTime.String()'s default layout + rfc3339Micro, + time.RFC3339Nano, + } ) // Transformer helps format the contents of an object to the user's liking. @@ -138,9 +147,14 @@ func NewTimeTransformer(layout string, location *time.Location) Transformer { rsp := fmt.Sprint(val) if valTime, ok := val.(time.Time); ok { rsp = formatTime(valTime) - } else if valStr, ok := val.(string); ok { - if valTime, err := time.Parse(time.RFC3339, valStr); err == nil { - rsp = formatTime(valTime) + } else { + // cycle through some supported layouts to see if the string form + // of the object matches any of these layouts + for _, possibleTimeLayout := range possibleTimeLayouts { + if valTime, err := time.Parse(possibleTimeLayout, rsp); err == nil { + rsp = formatTime(valTime) + break + } } } return rsp diff --git a/text/transformer_test.go b/text/transformer_test.go index e9bec90..e96de29 100644 --- a/text/transformer_test.go +++ b/text/transformer_test.go @@ -149,6 +149,9 @@ func TestNewTimeTransformer(t *testing.T) { expected := "2010-11-12T12:14:15-08:00" assert.Equal(t, expected, transformer(inStr)) assert.Equal(t, expected, transformer(inTime)) + for _, possibleTimeLayout := range possibleTimeLayouts { + assert.Equal(t, expected, transformer(inTime.Format(possibleTimeLayout)), possibleTimeLayout) + } location, err = time.LoadLocation("Asia/Singapore") assert.Nil(t, err) @@ -156,6 +159,9 @@ func TestNewTimeTransformer(t *testing.T) { expected = "Sat Nov 13 04:14:15 +08 2010" assert.Equal(t, expected, transformer(inStr)) assert.Equal(t, expected, transformer(inTime)) + for _, possibleTimeLayout := range possibleTimeLayouts { + assert.Equal(t, expected, transformer(inTime.Format(possibleTimeLayout)), possibleTimeLayout) + } location, err = time.LoadLocation("Europe/London") assert.Nil(t, err) @@ -163,6 +169,9 @@ func TestNewTimeTransformer(t *testing.T) { expected = "2010-11-12T20:14:15Z" assert.Equal(t, expected, transformer(inStr)) assert.Equal(t, expected, transformer(inTime)) + for _, possibleTimeLayout := range possibleTimeLayouts { + assert.Equal(t, expected, transformer(inTime.Format(possibleTimeLayout)), possibleTimeLayout) + } } func TestNewUnixTimeTransformer(t *testing.T) {