Skip to content

Commit

Permalink
WithUnixSeconds for unix timestamp
Browse files Browse the repository at this point in the history
Signed-off-by: JamesJJ <[email protected]>
  • Loading branch information
JamesJJ committed May 9, 2020
1 parent d3c5981 commit 7ffd962
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
12 changes: 11 additions & 1 deletion extension.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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
}
8 changes: 8 additions & 0 deletions options.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}
21 changes: 21 additions & 0 deletions strftime_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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!
Expand Down Expand Up @@ -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) {
Expand Down

0 comments on commit 7ffd962

Please sign in to comment.