You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
lib/types/timestamp.go

86 lines
1.6 KiB
Go

package types
import (
"time"
)
// 格式化
const (
FormatDate = "2006-01-02"
FormatDatetime = "2006-01-02 15:04:05"
)
// Local 本地時區
var Local = time.Local
// SetLocation 設定時區
func SetLocation(name string) {
Local, _ = time.LoadLocation(name)
}
// Timestamp 時間戳
type Timestamp int64
// GetUnixNow 取得現在時間戳記
func GetUnixNow() Timestamp {
return Timestamp(time.Now().Unix())
}
// GetUnix 嘗試取得時間戳記
func GetUnix(format, datetime string) (Timestamp, error) {
t, err := time.ParseInLocation(format, datetime, Local)
return Timestamp(t.Unix()), err
}
// MustGetUnix 強制取得時間戳記
func MustGetUnix(format, datetime string) Timestamp {
t, _ := GetUnix(format, datetime)
return t
}
// Int64 轉為64位元整數
func (t Timestamp) Int64() int64 {
return int64(t)
}
// Time 轉為time類型
func (t Timestamp) Time() time.Time {
return time.Unix(t.Int64(), 0)
}
// Date 回傳日期字串
func (t Timestamp) Date() string {
return time.
Unix(t.Int64(), 0).
In(Local).
Format(FormatDate)
}
// Datetime 回傳時間字串
func (t Timestamp) Datetime() string {
return time.
Unix(t.Int64(), 0).
In(Local).
Format(FormatDatetime)
}
// NowSub 與現在的時間差
func (t Timestamp) NowSub() time.Duration {
return time.Since(t.Time())
}
// Sub 時間差
func (t Timestamp) Sub(t2 time.Time) time.Duration {
return t2.Sub(t.Time())
}
// After 是否在指定時間後
func (t Timestamp) After(t2 time.Time) bool {
return t.Time().After(t2)
}
// AfterNow 是否在目前時間後
func (t Timestamp) AfterNow() bool {
return t.After(time.Now())
}