time2

package
v0.0.0-...-d31700d Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 28, 2022 License: MIT Imports: 9 Imported by: 0

README

time2

time2是对标准库time包的增强。包括:

  • 增加符合中文习惯的Time类型。
  • 增加日期类型:Date。
  • 增加时分秒类型:HMS。
  • 增强Duration类型:增加对年、月、日时间单位的支持,内置中英文时间单位,支持时间单位自定义。

Documentation

Overview

Package duration parse, format and calculate duration in full and customizable units.

Index

Examples

Constants

View Source
const (
	Year        int64 = 365 * Day
	Month             = 30 * Day
	Week              = 7 * Day
	Day               = 24 * Hour
	Hour              = 60 * Minute
	Minute            = 60 * Second
	Second            = 1000 * Millisecond
	Millisecond       = 1000 * Microsecond
	Microsecond       = 1000 * Nanosecond
	Nanosecond        = 1
)

Variables

View Source
var EN = []Unit{
	{Value: Year, Name: "Y", OtherNames: []string{"year", "years"}},
	{Value: Month, Name: "M", OtherNames: []string{"month", "months"}},
	{Value: Week, Name: "", OtherNames: []string{"W", "week", "weeks"}},
	{Value: Day, Name: "D", OtherNames: []string{"day", "days"}},

	{Value: Hour, Name: "h", OtherNames: []string{"hour", "hours"}},
	{Value: Minute, Name: "m", OtherNames: []string{"minute", "minutes"}},
	{Value: Second, Name: "s", OtherNames: []string{"second", "seconds"}},

	{Value: Millisecond, Name: "ms", OtherNames: []string{"millisecond", "milliseconds"}},
	{Value: Microsecond, Name: "us", OtherNames: []string{
		"µs",
		"μs",
		"microsecond", "microseconds",
	}},
	{Value: Nanosecond, Name: "ns", OtherNames: []string{"nanosecond", "nanoseconds"}},
}
View Source
var ZH = []Unit{
	{Value: Year, Name: "年", OtherNames: []string{}},
	{Value: Month, Name: "个月", OtherNames: []string{"月"}},
	{Value: Week, Name: "", OtherNames: []string{"周", "星期", "个星期"}},
	{Value: Day, Name: "天", OtherNames: []string{"日"}},

	{Value: Hour, Name: "小时", OtherNames: []string{"时"}},
	{Value: Minute, Name: "分", OtherNames: []string{"分钟"}},
	{Value: Second, Name: "秒", OtherNames: []string{"秒钟"}},

	{Value: Millisecond, Name: "毫秒", OtherNames: []string{}},
	{Value: Microsecond, Name: "微秒", OtherNames: []string{}},
	{Value: Nanosecond, Name: "纳秒", OtherNames: []string{}},
}

Functions

func RegisterUnitSet

func RegisterUnitSet(units []Unit) error

RegisterUnitSet register a set of units which will be used by Parse() and Duration.String().

Types

type Date

type Date struct {
	time.Time
}
Example (Compare)
day1 := NewDate(2021, 10, 1)
day2 := NewDate(2021, 10, 2)
day3 := NewDate(2021, 10, 2)
fmt.Println(day1.After(day2))
fmt.Println(day1.Before(day2))
fmt.Println(day1.Equal(day2))
fmt.Println(day2.After(day3))
fmt.Println(day2.Before(day3))
fmt.Println(day2.Equal(day3))
Output:

false
true
false
false
false
true

func NewDate

func NewDate(year, month, day int) Date

func NewDateFromTime

func NewDateFromTime(t time.Time) Date

func ParseDate

func ParseDate(str string) (Date, error)
Example
fmt.Println(ParseDate("2018-04-01"))
Output:

2018-04-01 <nil>

func Today

func Today() Date

func (Date) Add

func (date Date) Add(day int) Date

func (Date) After

func (t Date) After(u Date) bool

func (Date) Before

func (t Date) Before(u Date) bool

func (Date) Equal

func (t Date) Equal(u Date) bool

func (Date) MarshalJSON

func (date Date) MarshalJSON() ([]byte, error)
Example
var day = Date{}
b, err := json.Marshal(day)
fmt.Println(string(b), err)

day = NewDate(2018, 04, 01)
b, err = json.Marshal(day)
fmt.Println(string(b), err)
Output:

null <nil>
"2018-04-01" <nil>

func (*Date) Scan

func (date *Date) Scan(value interface{}) error

func (Date) String

func (date Date) String() string

func (Date) Sub

func (t Date) Sub(u Date) time.Duration

func (*Date) UnmarshalJSON

func (date *Date) UnmarshalJSON(b []byte) error
Example
var day = Date{}
err := json.Unmarshal([]byte(`"2019-09-12"`), &day)
fmt.Println(day, err)

day = Date{}
err = json.Unmarshal([]byte(`2019-09-12`), &day)
fmt.Println(day, err)
Output:

2019-09-12 <nil>
 invalid character '-' after top-level value

func (Date) Value

func (date Date) Value() (driver.Value, error)
Example
b, err := Date{}.Value()
fmt.Println(string(b.([]byte)), err)

day2 := NewDate(2018, 04, 01)
b, err = day2.Value()
fmt.Println(string(b.([]byte)), err)
Output:

NULL <nil>
'2018-04-01' <nil>

type Duration

type Duration struct {
	Value int64 // max duration: (1<<63 - 1) / (365 * 86400 * 1000 * 1000 * 1000) = 292 year
	Units []Unit
	N     int8 // String returns only the n most Signifcant units if n > 0.
}

func ParseDuration

func ParseDuration(s string) (Duration, error)

Parse like time.ParseDuration, no layout is needed. All registered units are recoganized.

Example (Empty)
fmt.Println(ParseDuration(``))
fmt.Println(ParseDuration(`0`))
fmt.Println(ParseDuration(`+0`))
fmt.Println(ParseDuration(`-0`))
Output:

0 <nil>
0 <nil>
0 <nil>
0 <nil>

func (Duration) Round

func (d Duration) Round(m int64) Duration

Round returns the result of rounding d to the nearest multiple of m. The rounding behavior for halfway values is to round away from zero. If the result exceeds the maximum (or minimum) value that can be stored in a Duration, Round returns the maximum (or minimum) duration. If m <= 0, Round returns d unchanged.

Example
d, _ := ParseDuration(`2m29s`)
fmt.Println(d.Round(Minute))

d, _ = ParseDuration(`2m30s`)
fmt.Println(d.Round(Minute))

d, _ = ParseDuration(`-2m29s`)
fmt.Println(d.Round(Minute))

d, _ = ParseDuration(`-2m30s`)
fmt.Println(d.Round(Minute))
Output:

2m
3m
-2m
-3m

func (Duration) String

func (d Duration) String() (s string)
Example
d, _ := ParseDuration(`2m3s`)
fmt.Println(d)

d, _ = ParseDuration(`-1Y2M9D13h5m`)
d.N = 2
fmt.Println(d)
Output:

2m3s
-1Y2M

func (Duration) Truncate

func (d Duration) Truncate(m int64) Duration

Truncate returns the result of rounding d toward zero to a multiple of m. If m <= 0, Truncate returns d unchanged.

Example
d, _ := ParseDuration(`2m3s`)
fmt.Println(d.Truncate(Minute))

d, _ = ParseDuration(`-1Y2M9D13h5m`)
fmt.Println(d.Truncate(Day))
Output:

2m
-1Y2M9D

func (*Duration) UnmarshalJSON

func (d *Duration) UnmarshalJSON(b []byte) error
Example
var d Duration
if err := json.Unmarshal([]byte(`"123秒"`), &d); err != nil {
	fmt.Println(err)
}
fmt.Println(d)
Output:

2分3秒

func (*Duration) UnmarshalYAML

func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error
Example
var d Duration
if err := yaml.Unmarshal([]byte(`123秒`), &d); err != nil {
	fmt.Println(err)
}
fmt.Println(d)

if err := yaml.Unmarshal([]byte(`"123秒"`), &d); err != nil {
	fmt.Println(err)
}
fmt.Println(d)
Output:

2分3秒
2分3秒

type HMS

type HMS struct {
	time.Time
}

HMS reprenets hour, minute, second.

Example
type Stu struct {
	Name       string `json:"name"`
	FinishedAt HMS    `json:"finishedAt"`
}

d, err := NewHMS("14:05:00")
fmt.Println(err)

stu := Stu{Name: "A", FinishedAt: *d}
b, _ := json.Marshal(stu)
fmt.Println(string(b))

stu = Stu{Name: "A"}
b, _ = json.Marshal(stu)
fmt.Println(string(b))

stu2 := Stu{}
data := []byte(`{"name": "W5"}`)
json.Unmarshal(data, &stu2)
fmt.Println(stu2.FinishedAt.IsZero())

data = []byte(`{"name": "W5", "finishedAt": ""}`)
json.Unmarshal(data, &stu2)
fmt.Println(stu2.FinishedAt)

fmt.Println(NewHMS("24:00:00"))
Output:

<nil>
{"name":"A","finishedAt":"14:05:00"}
{"name":"A","finishedAt":null}
true
00:00:00
23:59:59 <nil>

func NewHMS

func NewHMS(str string) (*HMS, error)

func (HMS) MarshalJSON

func (hms HMS) MarshalJSON() ([]byte, error)

func (HMS) OfToday

func (hms HMS) OfToday() time.Time

OfToday return the time(hour,minute,second) of today.

func (*HMS) Scan

func (hms *HMS) Scan(value interface{}) error

func (HMS) String

func (hms HMS) String() string

func (*HMS) UnmarshalJSON

func (hms *HMS) UnmarshalJSON(b []byte) (err error)

func (HMS) Value

func (hms HMS) Value() (driver.Value, error)

type Sleep

type Sleep struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

func (*Sleep) Asleep

func (s *Sleep) Asleep() bool
Example
package main

import (
	"fmt"
	"time"

	"gitee.com/go-better/dev/type/time2"
)

func main() {
	var s time2.Sleep
	go func() {
		time.Sleep(time.Millisecond)
		fmt.Println(s.Asleep())
		time.Sleep(2 * time.Millisecond)
		fmt.Println(s.Asleep())
	}()
	s.Sleep(2*time.Millisecond, nil)
	fmt.Println(s.Asleep())
	time.Sleep(5 * time.Millisecond)
}
Output:

true
false
false

func (*Sleep) Awake

func (s *Sleep) Awake(event interface{})

the same as s.AwakeAt(time.Now())

Example
package main

import (
	"fmt"
	"time"

	"gitee.com/go-better/dev/type/time2"
)

func main() {
	var s time2.Sleep
	go func() {
		fmt.Println(s.Sleep(time.Minute, nil))
	}()
	time.Sleep(time.Millisecond)
	s.Awake("hi, wake up")
	time.Sleep(5 * time.Millisecond)

}
Output:

hi, wake up

func (*Sleep) AwakeAt

func (s *Sleep) AwakeAt(at time.Time, event interface{})

set awake at time to the specified time, and awake at the specified time if asleep.

func (*Sleep) AwakeAtEalier

func (s *Sleep) AwakeAtEalier(at time.Time, event interface{})

if current awake at time is zero time or the specified time is ealier than current awake at time, call s.AwakeAt(at), otherwise do nothing.

func (*Sleep) AwakeAtLater

func (s *Sleep) AwakeAtLater(at time.Time, event interface{})

if the specified time is later than current awake at time, call s.AwakeAt(at), otherwise do nothing.

func (*Sleep) ClearAwakeAt

func (s *Sleep) ClearAwakeAt()

set awake at time to zero time.

func (*Sleep) GetAwakeAt

func (s *Sleep) GetAwakeAt() time.Time

get awake at time.

Example
package main

import (
	"fmt"

	"gitee.com/go-better/dev/type/time2"
)

func main() {
	var s time2.Sleep
	s.Sleep(0, nil)
	fmt.Println(s.GetAwakeAt().IsZero())
	s.ClearAwakeAt()
	fmt.Println(s.GetAwakeAt().IsZero())
}
Output:

false
true

func (*Sleep) Run

func (s *Sleep) Run() interface{}

Run method on a single `Sleep` instance should not be called concurrently, otherwise only a random one will be awaken up by `Awake*` methods. Run method on a single `Sleep` instance can be called many times serially. Run returns the event that awaken it.

func (*Sleep) SetAwakeAt

func (s *Sleep) SetAwakeAt(at time.Time, event interface{})

set awake at time.

func (*Sleep) Sleep

func (s *Sleep) Sleep(d time.Duration, event interface{}) interface{}

Sleep method on a single `Sleep` instance should not be called concurrently, otherwise only a random one will be awaken up by `Awake*` methods. Sleep method on a single `Sleep` instance can be called many times serially. Sleep returns the event that awaken it.

Example
package main

import (
	"fmt"
	"time"

	"gitee.com/go-better/dev/type/time2"
)

func main() {
	var s time2.Sleep
	go func() {
		fmt.Println(s.Sleep(0, "wake up"))
	}()
	time.Sleep(5 * time.Millisecond)
}
Output:

wake up

type Time

type Time struct {
	time.Time
}

func New

func New(year, month, day, hour, minute, second int) Time

func Now

func Now() Time

func Parse

func Parse(str string) (Time, error)
Example
fmt.Println(Parse("2019-09-12 12:01:02"))
Output:

2019-09-12 12:01:02 <nil>

func (Time) MarshalJSON

func (t Time) MarshalJSON() ([]byte, error)
Example
var t = Time{}
b, err := json.Marshal(t)
fmt.Println(string(b), err)

t = New(2019, 9, 12, 12, 1, 2)
b, err = json.Marshal(t)
fmt.Println(string(b), err)
Output:

null <nil>
"2019-09-12 12:01:02" <nil>

func (*Time) Scan

func (t *Time) Scan(value interface{}) error

func (Time) String

func (t Time) String() string

func (*Time) UnmarshalJSON

func (t *Time) UnmarshalJSON(b []byte) error
Example
var t = Time{}
err := json.Unmarshal([]byte(`"2019-09-12 12:01:02"`), &t)
fmt.Println(t, err)

t = Time{}
err = json.Unmarshal([]byte(`2019-09-12 12:01:02`), &t)
fmt.Println(t, err)
Output:

2019-09-12 12:01:02 <nil>
 invalid character '-' after top-level value

func (Time) Value

func (t Time) Value() (driver.Value, error)
Example
b, err := Time{}.Value()
fmt.Println(string(b.([]byte)), err)

t := Time{time.Date(2019, 9, 12, 12, 1, 2, 0, time.UTC)}
b, err = t.Value()
fmt.Println(string(b.([]byte)), err)
Output:

NULL <nil>
'2019-09-12T12:01:02Z' <nil>

type Unit

type Unit struct {
	Value      int64    // How many nanoseconds the unit has.
	Name       string   // If Name field is empty, the unit will not be used by Duration.Format.
	PluralName string   // Name in plural form, optional.
	OtherNames []string // Other names, optional.
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL