Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(os/gtime): SetStringLayout #4130

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 28 additions & 1 deletion os/gtime/gtime_time_wrapper.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,36 @@
package gtime

import (
"sync"
"time"
)

var (
setStringLayoutMu sync.Mutex
setStringLayout = "2006-01-02T15:04:05-07:00"
)

// SetStringLayout sets the default string layout for function String.
// The default string layout is "2006-01-02 15:04:05".
// It's used for overwriting the default string layout for time.Time.String.
//
// You can set it to time.RFC3339 for example.
func SetStringLayout(layout string) {
setStringLayoutMu.Lock()
defer setStringLayoutMu.Unlock()
setStringLayout = layout
}

// SetStringISO8601 sets the default string layout to ISO8601 for function String.
func SetStringISO8601() {
SetStringLayout("2006-01-02T15:04:05-07:00")
}

// SetStringRFC822 sets the default string layout to RFC822 for function String.
func SetStringRFC822() {
SetStringLayout("Mon, 02 Jan 06 15:04 MST")
}

// wrapper is a wrapper for stdlib struct time.Time.
// It's used for overwriting some functions of time.Time, for example: String.
type wrapper struct {
Expand All @@ -25,5 +52,5 @@ func (t wrapper) String() string {
// Only time.
return t.Format("15:04:05")
}
return t.Format("2006-01-02 15:04:05")
return t.Format(setStringLayout)
}
32 changes: 32 additions & 0 deletions os/gtime/gtime_z_example_wrapper_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package gtime_test

import (
"fmt"
"time"

"github.com/gogf/gf/v2/os/gtime"
)

func ExampleSetStringLayout() {
gtime.SetStringLayout(time.RFC3339)
fmt.Println(gtime.New("2025-01-21 14:08:05").String())

// Output:
// 2025-01-21T14:08:05+08:00
}

func ExampleSetStringISO8601() {
gtime.SetStringISO8601()
fmt.Println(gtime.New("2025-01-21 14:10:12").String())

// Output:
// 2025-01-21T14:10:12+08:00
}

func ExampleSetStringRFC822() {
gtime.SetStringRFC822()
fmt.Println(gtime.New("2025-01-21 14:11:32").String())

// Output:
// Tue, 21 Jan 25 14:11 CST
}
Loading