2023-07-21 17:07:04 +08:00
|
|
|
|
package timex
|
|
|
|
|
|
|
2024-01-05 08:55:34 +08:00
|
|
|
|
import (
|
|
|
|
|
|
"context"
|
|
|
|
|
|
"database/sql"
|
|
|
|
|
|
"encoding/json"
|
|
|
|
|
|
"time"
|
|
|
|
|
|
)
|
2023-07-21 17:07:04 +08:00
|
|
|
|
|
2023-12-29 16:48:15 +08:00
|
|
|
|
const DefaultDateTimeFormat = "2006-01-02 15:04:05"
|
|
|
|
|
|
|
2024-10-21 22:27:42 +08:00
|
|
|
|
// DefaultFormat 使用默认格式进行格式化: 2006-01-02 15:04:05
|
2023-07-21 17:07:04 +08:00
|
|
|
|
func DefaultFormat(time time.Time) string {
|
2023-12-29 16:48:15 +08:00
|
|
|
|
return time.Format(DefaultDateTimeFormat)
|
2023-07-21 17:07:04 +08:00
|
|
|
|
}
|
2024-01-05 08:55:34 +08:00
|
|
|
|
|
2024-10-21 22:27:42 +08:00
|
|
|
|
// TimeNo 获取当前时间编号,格式为20060102150405
|
|
|
|
|
|
func TimeNo() string {
|
|
|
|
|
|
return time.Now().Format("20060102150405")
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2024-01-05 08:55:34 +08:00
|
|
|
|
func NewNullTime(t time.Time) NullTime {
|
|
|
|
|
|
return NullTime{
|
|
|
|
|
|
NullTime: sql.NullTime{
|
|
|
|
|
|
Time: t,
|
|
|
|
|
|
Valid: !t.IsZero(),
|
|
|
|
|
|
},
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
type NullTime struct {
|
|
|
|
|
|
sql.NullTime
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
func (nt *NullTime) UnmarshalJSON(bytes []byte) error {
|
|
|
|
|
|
if len(bytes) == 0 {
|
|
|
|
|
|
nt.NullTime = sql.NullTime{}
|
|
|
|
|
|
return nil
|
|
|
|
|
|
}
|
|
|
|
|
|
var t time.Time
|
|
|
|
|
|
if err := json.Unmarshal(bytes, &t); err != nil {
|
|
|
|
|
|
return err
|
|
|
|
|
|
}
|
|
|
|
|
|
if t.IsZero() {
|
|
|
|
|
|
nt.NullTime = sql.NullTime{}
|
|
|
|
|
|
return nil
|
|
|
|
|
|
}
|
|
|
|
|
|
nt.NullTime = sql.NullTime{
|
|
|
|
|
|
Valid: true,
|
|
|
|
|
|
Time: t,
|
|
|
|
|
|
}
|
|
|
|
|
|
return nil
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
func (nt *NullTime) MarshalJSON() ([]byte, error) {
|
|
|
|
|
|
if !nt.Valid || nt.Time.IsZero() {
|
|
|
|
|
|
return json.Marshal(nil)
|
|
|
|
|
|
}
|
|
|
|
|
|
return json.Marshal(nt.Time)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
func SleepWithContext(ctx context.Context, d time.Duration) {
|
2024-01-15 20:11:28 +08:00
|
|
|
|
timer := time.NewTimer(d)
|
|
|
|
|
|
defer timer.Stop()
|
|
|
|
|
|
select {
|
|
|
|
|
|
case <-timer.C:
|
|
|
|
|
|
case <-ctx.Done():
|
|
|
|
|
|
}
|
2024-01-05 08:55:34 +08:00
|
|
|
|
}
|