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

122 lines
2.4 KiB
Go

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