From 7ffd9624621ef8888e48507b8668a66427dda10b Mon Sep 17 00:00:00 2001 From: JamesJJ Date: Sat, 9 May 2020 20:35:05 +0800 Subject: [PATCH] WithUnixSeconds for unix timestamp Signed-off-by: JamesJJ --- extension.go | 12 +++++++++++- options.go | 8 ++++++++ strftime_test.go | 21 +++++++++++++++++++++ 3 files changed, 40 insertions(+), 1 deletion(-) diff --git a/extension.go b/extension.go index b0218b9..bd411d6 100644 --- a/extension.go +++ b/extension.go @@ -10,6 +10,7 @@ import ( // This way, `go doc -all` does not show the contents of the // milliseconds function var milliseconds Appender +var unixseconds Appender func init() { milliseconds = AppendFunc(func(b []byte, t time.Time) []byte { @@ -22,10 +23,19 @@ func init() { } return append(b, strconv.Itoa(millisecond)...) }) + unixseconds = AppendFunc(func(b []byte, t time.Time) []byte { + return append(b, strconv.FormatInt(t.Unix(), 10)...) + }) } // Milliseconds returns the Appender suitable for creating a zero-padded, // 3-digit millisecond textual representation. -func Milliseconds() Appender { +func Milliseconds() Appender { return milliseconds } + +// UnixSeconds returns the Appender suitable for creating +// unix timestamp textual representation. +func UnixSeconds() Appender { + return unixseconds +} diff --git a/options.go b/options.go index 8697a9b..889653d 100644 --- a/options.go +++ b/options.go @@ -49,3 +49,11 @@ func WithSpecification(b byte, a Appender) Option { func WithMilliseconds(b byte) Option { return WithSpecification(b, Milliseconds()) } + +// WithUnixSeconds is similar to WithSpecification, and specifies that +// the Strftime object should interpret the pattern `%b` (where b +// is the byte that you specify as the argument) +// as the unix timestamp in seconds +func WithUnixSeconds(b byte) Option { + return WithSpecification(b, UnixSeconds()) +} diff --git a/strftime_test.go b/strftime_test.go index 05122ee..1a651ac 100644 --- a/strftime_test.go +++ b/strftime_test.go @@ -158,6 +158,15 @@ func TestGHPR7(t *testing.T) { } } +func TestWithUnixSeconds(t *testing.T) { + const expected = `1136239445` + + p, _ := strftime.New(`%s`, strftime.WithUnixSeconds('s')) + if !assert.Equal(t, expected, p.FormatString(ref), `patterns should match for custom specification`) { + return + } +} + func Example_CustomSpecifications() { { // I want %L as milliseconds! @@ -208,11 +217,23 @@ func Example_CustomSpecifications() { os.Stdout.Write([]byte{'\n'}) } + { + // I want %s as unix timestamp! + p, err := strftime.New(`%s`, strftime.WithUnixSeconds('s')) + if err != nil { + fmt.Println(err) + return + } + p.Format(os.Stdout, ref) + os.Stdout.Write([]byte{'\n'}) + } + // OUTPUT: // 123 // 123 // Daisuke Maki // Daisuke Maki + // 1136239445 } func TestGHIssue9(t *testing.T) {