Skip to content

Commit

Permalink
优化
Browse files Browse the repository at this point in the history
  • Loading branch information
zgwit committed Oct 29, 2024
1 parent f4272ba commit 82597c2
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 31 deletions.
21 changes: 21 additions & 0 deletions pkg/time/quick.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package time

import (
"sync"
"time"
)

var quick Time
var once sync.Once

func Quick() Time {
once.Do(func() {
go func() {
for {
quick = Now()
time.Sleep(time.Second)
}
}()
})
return quick
}
45 changes: 14 additions & 31 deletions pkg/time/time.go
Original file line number Diff line number Diff line change
@@ -1,50 +1,48 @@
package time

import (
"sync"
"time"
)

const localDateTimeFormat string = "2006-01-02 15:04:05"

type Time time.Time
type Time struct {
time.Time
}

func (t *Time) MarshalJSON() ([]byte, error) {
b := make([]byte, 0, len(localDateTimeFormat)+2)
b = append(b, '"')
b = time.Time(*t).AppendFormat(b, localDateTimeFormat)
b = t.AppendFormat(b, localDateTimeFormat)
b = append(b, '"')
return b, nil
}

func (t *Time) UnmarshalJSON(b []byte) error {
now, err := time.ParseInLocation(`"`+localDateTimeFormat+`"`, string(b), time.Local)
*t = Time(now)
tm, err := time.ParseInLocation(`"`+localDateTimeFormat+`"`, string(b), time.Local)
*t = Time{tm}
return err
}

func (t *Time) String() string {
return time.Time(*t).Format(localDateTimeFormat)
}

func (t *Time) Now() Time {
return Time(time.Now())
}

func (t *Time) ParseTime(tm time.Time) Time {
return Time(tm)
return t.Format(localDateTimeFormat)
}

func (t *Time) format() string {
return time.Time(*t).Format(localDateTimeFormat)
return t.Format(localDateTimeFormat)
}

func (t *Time) MarshalText() ([]byte, error) {
return []byte(t.format()), nil
}

func Now() Time {
return Time(time.Now())
return Time{time.Now()}
}

func Parse(str string) (Time, error) {
tm, err := time.Parse(str, localDateTimeFormat)
return Time{tm}, err
}

func After(ms int64, fn func()) {
Expand All @@ -54,18 +52,3 @@ func After(ms int64, fn func()) {
func Sleep(ms int64, fn func()) {
time.Sleep(time.Duration(ms) * time.Millisecond)
}

var quick Time
var once sync.Once

func Quick() Time {
once.Do(func() {
go func() {
for {
quick = Now()
time.Sleep(time.Second)
}
}()
})
return quick
}
17 changes: 17 additions & 0 deletions pkg/time/time_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package time

import (
"encoding/json"
"testing"
)

func TestTime_MarshalJSON(t *testing.T) {
var abc = struct {
Tm Time
}{
Tm: Now(),
}

buf, err := json.Marshal(&abc)
println(string(buf), err)
}

0 comments on commit 82597c2

Please sign in to comment.