moment

package
v0.19.4 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2026 License: Apache-2.0 Imports: 6 Imported by: 0

Documentation

Overview

* @Author: kamalyes 501893067@qq.com * @Date: 2023-07-28 00:50:58 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-12-03 15:41:12 * @FilePath: \go-toolbox\pkg\moment\base.go * @Description: * * Copyright (c) 2024 by kamalyes, All Rights Reserved.

* @Author: kamalyes 501893067@qq.com * @Date: 2023-07-28 00:50:58 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-06-18 11:20:07 * @FilePath: \go-toolbox\pkg\moment\constants.go * @Description: * * Copyright (c) 2024 by kamalyes, All Rights Reserved.

* @Author: kamalyes 501893067@qq.com * @Date: 2025-01-09 19:15:01 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-02-19 10:32:50 * @FilePath: \go-toolbox\pkg\moment\timer.go * @Description: * * Copyright (c) 2025 by kamalyes, All Rights Reserved.

Index

Constants

View Source
const (
	// 默认时区
	DefaultTimezone = "Asia/Shanghai"

	// 默认时间格式
	DefaultTimeFormat = "2006-01-02 15:04:05"

	// 紧凑格式 - 用于文件名、日志、缓存键等场景
	CompactDateFormat          = "20060102"           // 紧凑日期格式 YYYYMMDD
	CompactDateHourFormat      = "2006010215"         // 紧凑日期+小时格式 YYYYMMDDHH
	CompactDateTimeFormat      = "200601021504"       // 紧凑日期时间格式 YYYYMMDDHHMM
	CompactDateTimeSecFormat   = "20060102150405"     // 紧凑日期时间秒格式 YYYYMMDDHHMMSS
	CompactDateTimeMilliFormat = "20060102150405.000" // 紧凑日期时间毫秒格式 YYYYMMDDHHMMSS.sss

	// 纳秒,作为最基础的时间单位
	NanosecondDuration time.Duration = 1

	// 微秒,表示1微秒持续的纳秒时长
	MicrosecondDuration = 1000 * NanosecondDuration

	// 毫秒,表示1毫秒持续的纳秒时长
	MillisecondDuration = 1000 * MicrosecondDuration

	// 秒,表示1秒持续的纳秒时长
	SecondDuration = 1000 * MillisecondDuration

	// 分钟,表示1分钟持续的纳秒时长
	MinuteDuration = 60 * SecondDuration

	// 小时,表示1小时持续的纳秒时长
	HourDuration = 60 * MinuteDuration

	// 天,表示1天持续的纳秒时长
	// 这里不考虑夏时制问题,泛指国际基础单位制(民用日)所理解的时间
	DayDuration = 24 * HourDuration

	// 周,表示1周持续的纳秒时长
	// 这里不考虑夏时制问题,泛指国际基础单位制(民用日)所理解的时间
	WeekDuration = 7 * DayDuration

	// 月,表示30天
	Month28Duration = 28 * DayDuration

	// 月,表示29天,等于28天加1天
	Month29Duration = Month28Duration + 1*DayDuration

	// 月,表示30天,等于28天加2天
	Month30Duration = Month28Duration + 2*DayDuration

	// 年,表示365天(平年)
	Year365Duration = 365 * DayDuration

	// 年,表示366天(闰年),等于365天加1天
	Year366Duration = Year365Duration + 1*DayDuration
)

通用的时间单位持续时长,这里泛指国际基础单位制(民用日)所理解的时间,不考虑夏时制,不用作科学与天文学

Variables

This section is empty.

Functions

func CalculateAge

func CalculateAge(birthday string, currentTime time.Time) (int, error)

计算年龄的函数,currentTime 为计算年龄时的参考时间

func CalculateBirthDate

func CalculateBirthDate(age int) time.Time

CalculateBirthDate 根据年龄计算出生日期

func CalculateStartAndEndTime

func CalculateStartAndEndTime(year int, month time.Month, day int, duration time.Duration) (int64, int64)

CalculateStartAndEndTime 根据给定的年、月、日和持续时间计算开始和结束时间

func CharToCode

func CharToCode(layout string) string

将自定义布局字符替换为 Go 时间格式

func ConvertStringToTimestamp

func ConvertStringToTimestamp(dateString, layout string, timeZone string) (int64, error)

ConvertStringToTimestamp String时间类型转换为时间戳

func CurrentMicrosecond

func CurrentMicrosecond() int64

获取当前时间的微秒数

func CurrentMillisecond

func CurrentMillisecond() int64

获取当前时间的毫秒数

func CurrentNanosecond

func CurrentNanosecond() int64

获取当前时间的纳秒数

func Day

func Day(t ...time.Time) int

获取日期

func DayOfYear

func DayOfYear(year int, n int) time.Time

DayOfYear 获取指定年份的第n天,时分秒归零

func DaysInMonth

func DaysInMonth(year int, month time.Month) int

DaysInMonth 计算指定年月的天数

func FormatCompact

func FormatCompact(t time.Time, format string) string

FormatCompact 使用紧凑格式格式化时间 参数:

  • t: 要格式化的时间
  • format: 紧凑格式类型(使用 CompactXxxFormat 常量)

返回: 格式化后的字符串

示例:

FormatCompact(time.Now(), CompactDateFormat)         // "20060102"
FormatCompact(time.Now(), CompactDateHourFormat)     // "2006010215"
FormatCompact(time.Now(), CompactDateTimeFormat)     // "200601021504"
FormatCompact(time.Now(), CompactDateTimeSecFormat)  // "20060102150405"

func FormatCompactDate

func FormatCompactDate(t time.Time) string

FormatCompactDate 格式化为紧凑日期格式 (YYYYMMDD)

func FormatCompactDateHour

func FormatCompactDateHour(t time.Time) string

FormatCompactDateHour 格式化为紧凑日期+小时格式 (YYYYMMDDHH)

func FormatCompactDateTime

func FormatCompactDateTime(t time.Time) string

FormatCompactDateTime 格式化为紧凑日期时间格式 (YYYYMMDDHHMM)

func FormatCompactDateTimeMilli

func FormatCompactDateTimeMilli(t time.Time) string

FormatCompactDateTimeMilli 格式化为紧凑日期时间毫秒格式 (YYYYMMDDHHMMSS.sss)

func FormatCompactDateTimeSec

func FormatCompactDateTimeSec(t time.Time) string

FormatCompactDateTimeSec 格式化为紧凑日期时间秒格式 (YYYYMMDDHHMMSS)

func FormatWithLocation

func FormatWithLocation(timezone string, ts int64, defaultDateFormat string) string

FormatWithLocation 国际化时间戳转换字符串

func GetCurrentTimeInfo

func GetCurrentTimeInfo() (string, int, time.Time)

GetCurrentTimeInfo 获取当前日期、小时和时间的通用函数

func GetServerTimezone

func GetServerTimezone() string

GetServerTimezone 获取服务器的本地时区信息

func GetTimeOffset

func GetTimeOffset(timezone string, ts int64) (offset int)

GetTimeOffset 国际化时间戳偏移

func Hour

func Hour(t ...time.Time) int

获取小时

func HumanDuration

func HumanDuration(start, end time.Time) string

HumanDuration 计算两个时间点之间的年月日时分秒差距, 并返回一个中文格式的字符串,比如“1年零2个月零3天零4小时零5分零6秒” start 和 end 可任意顺序,函数内部会自动调整顺序

func LastDayOfMonth

func LastDayOfMonth(year int, month time.Month) time.Time

LastDayOfMonth 获取当月最后一天,时分秒归零

func LastNDays

func LastNDays(num int) (int64, int64)

最近N天的开始和结束时间

func LastNMonths

func LastNMonths(num int) (int64, int64)

最近N个月的开始和结束时间

func LastNWeeks

func LastNWeeks(num int) (int64, int64)

最近N周的开始和结束时间

func LastNYears

func LastNYears(num int) (int64, int64)

最近N年的开始和结束时间

func LastWeekdayOfMonth

func LastWeekdayOfMonth(year int, month time.Month, target time.Weekday) time.Time

LastWeekdayOfMonth 获取当月最后一个指定星期几(如最后一个周五) 返回时间,时分秒归零

func Minute

func Minute(t ...time.Time) int

获取分钟

func Month

func Month(t ...time.Time) int

获取月份

func NextWeekday

func NextWeekday(year int, month time.Month, day int, target time.Weekday) time.Time

NextWeekday 返回指定日期的下一个目标星期几 如果当天是目标星期几,则返回下一周的同一天(加7天)

func NextWorkDay

func NextWorkDay(year int, month time.Month, day int) time.Time

NextWorkDay 返回指定日期的下一个工作日(周一至周五) 规则说明: - 输入日期是周一到周四,返回下一天(一定是工作日) - 输入日期是周五,返回下周一(跳过周六、周日) - 输入日期是周六,返回下周一(加2天) - 输入日期是周日,返回下周一(加1天) 跨月跨年由 time.AddDate 自动处理,无需额外判断

func NowCompactDate

func NowCompactDate() string

NowCompactDate 获取当前时间的紧凑日期格式 (YYYYMMDD)

func NowCompactDateHour

func NowCompactDateHour() string

NowCompactDateHour 获取当前时间的紧凑日期+小时格式 (YYYYMMDDHH)

func NowCompactDateTime

func NowCompactDateTime() string

NowCompactDateTime 获取当前时间的紧凑日期时间格式 (YYYYMMDDHHMM)

func NowCompactDateTimeMilli

func NowCompactDateTimeMilli() string

NowCompactDateTimeMilli 获取当前时间的紧凑日期时间毫秒格式 (YYYYMMDDHHMMSS.sss)

func NowCompactDateTimeSec

func NowCompactDateTimeSec() string

NowCompactDateTimeSec 获取当前时间的紧凑日期时间秒格式 (YYYYMMDDHHMMSS)

func NowTime

func NowTime(t []time.Time) time.Time

NowTime 获取时间的辅助函数

func ParseCompact

func ParseCompact(value string, format string) (time.Time, error)

ParseCompact 解析紧凑格式的时间字符串 参数:

  • value: 紧凑格式的时间字符串
  • format: 紧凑格式类型(使用 CompactXxxFormat 常量)

返回: 解析后的时间和可能的错误

示例:

ParseCompact("20240214", CompactDateFormat)         // 解析日期 2024-02-14
ParseCompact("2024021415", CompactDateHourFormat)   // 解析日期+小时 2024-02-14 15:00
ParseCompact("202402141530", CompactDateTimeFormat) // 解析日期+时间 2024-02-14 15:30

func ParseFlexibleDate

func ParseFlexibleDate(dateStr string) (time.Time, error)

func ParseWithLocation

func ParseWithLocation(timezone string, timeStr string, defaultDateFormat string) int64

ParseWithLocation 国际化时间字符串转换时间戳

func SafeParseTimeToUnixNano

func SafeParseTimeToUnixNano(timeStr string) int64

SafeParseTimeToUnixNano

func Second

func Second(t ...time.Time) int

获取秒

func StrtoTime

func StrtoTime(s string, format ...string) (time.Time, error)

字符串转换为 time.Time

func Today

func Today() (int64, int64)

今天的开始和结束时间

func TrackTime

func TrackTime(pre time.Time) time.Duration

TrackTime 跟踪时间

func Year

func Year(t ...time.Time) int

获取年份

func YearDay

func YearDay(t ...time.Time) int

获取一年中的第几天

func Yesterday

func Yesterday() (int64, int64)

昨天的开始和结束时间

Types

type Moment

type Moment struct {
	// contains filtered or unexported fields
}

Moment 包装 time.Time 的链式时间值

值类型,可直接复制;零值等价于 time.Time 的零值

func From

func From(t time.Time) Moment

From 由 time.Time 构造

func FromUnix

func FromUnix(sec, nsec int64) Moment

FromUnix 由 Unix 秒与纳秒构造

func Now

func Now() Moment

Now 返回当前时刻

func (Moment) Add

func (m Moment) Add(n int, u Unit) Moment

Add 按单位加 n,n 可为负

天与周走 AddDate 而不是乘 24 小时:有夏令时的时区里一天不总是 24 小时, 乘 24 小时会在切换日把时刻挪错一小时 月、季、年按月份推进并把日钳到目标月末,见 addMonths

[EN] Adds n of the given unit; n may be negative. Days and weeks go through AddDate rather than multiplying by 24 hours, because a day is not always 24 hours where daylight saving applies and multiplying shifts the clock by an hour on the switching day. Months, quarters and years advance by month and clamp the day to the end of the target month

func (Moment) After

func (m Moment) After(other Moment) bool

func (Moment) Before

func (m Moment) Before(other Moment) bool

比较

func (Moment) Day

func (m Moment) Day() int

func (Moment) Diff

func (m Moment) Diff(other Moment, u Unit) int

Diff 返回 m 减 other 的差值,以该单位计,向零取整

月、季、年按日历计算而不是按固定天数相除:按天数除会把二月与七月当成一样长 做法是先比月份差,再看日与时分秒是否已经走满一个月

[EN] The difference between m and other in the given unit, truncated toward zero. Months, quarters and years are counted by calendar rather than by dividing a fixed number of days, which would treat February and July as equally long: the month difference is taken first, then adjusted by whether the day and clock time have completed a whole month

func (Moment) EndOf

func (m Moment) EndOf(u Unit) Moment

EndOf 取该单位的结束时刻,即最后一纳秒

dayjs 到毫秒为止,而 Go 的精度到纳秒,这里不自降精度 用「下一单位的起点减一纳秒」算,天然处理月末、闰年与夏令时

[EN] The end of the unit, its last nanosecond. dayjs stops at milliseconds while Go has nanosecond precision, which is not given up here. Computed as the next unit's start minus one nanosecond, which handles month ends, leap years and daylight saving for free

func (Moment) EndOfWeekOn

func (m Moment) EndOfWeekOn(start time.Weekday) Moment

EndOfWeekOn 取本周结束时刻,周的起点由 start 指定

func (Moment) Equal

func (m Moment) Equal(other Moment) bool

func (Moment) Format

func (m Moment) Format(layout string) string

Format 按 layout 格式化

func (Moment) Hour

func (m Moment) Hour() int

func (Moment) In

func (m Moment) In(loc *time.Location) Moment

In 换到指定时区,时刻本身不变

func (Moment) IsZero

func (m Moment) IsZero() bool

IsZero 是否为零值时刻

func (Moment) Minute

func (m Moment) Minute() int

func (Moment) Month

func (m Moment) Month() time.Month

func (Moment) Nanosecond

func (m Moment) Nanosecond() int

func (Moment) Quarter

func (m Moment) Quarter() int

Quarter 返回季度,1 到 4

func (Moment) Second

func (m Moment) Second() int

func (Moment) StartOf

func (m Moment) StartOf(u Unit) Moment

StartOf 取该单位的起始时刻

周的起点取周一(ISO 8601,也是中文习惯),dayjs 默认周日,需要别的起点用 StartOfWeekOn

[EN] The start of the given unit. The week starts on Monday per ISO 8601, where dayjs defaults to Sunday; use StartOfWeekOn for another start

func (Moment) StartOfWeekOn

func (m Moment) StartOfWeekOn(start time.Weekday) Moment

StartOfWeekOn 取本周起始时刻,周的起点由 start 指定

[EN] The start of the week, with the week's first day given by start

func (Moment) String

func (m Moment) String() string

String 按 DefaultTimeFormat 格式化,便于打印

func (Moment) Sub

func (m Moment) Sub(n int, u Unit) Moment

Sub 按单位减 n

func (Moment) Time

func (m Moment) Time() time.Time

Time 取出底层的 time.Time

func (Moment) Unix

func (m Moment) Unix() int64

Unix 返回 Unix 秒

func (Moment) UnixMilli

func (m Moment) UnixMilli() int64

UnixMilli 返回 Unix 毫秒

func (Moment) Weekday

func (m Moment) Weekday() time.Weekday

func (Moment) Year

func (m Moment) Year() int

日期与时间分量

type TimeDifference

type TimeDifference struct {
	Years   int
	Days    int
	Hours   int
	Minutes int
	Seconds int
}

TimeDifference 结构体用于存储年、天、小时、分钟和秒

func CalculateTimeDifference

func CalculateTimeDifference(duration time.Duration) TimeDifference

CalculateTimeDifference 计算给定的 time.Duration,并返回 TimeDifference

type Timer

type Timer struct {
	// contains filtered or unexported fields
}

Timer 结构体用于表示一个计时器

func NewTimer

func NewTimer() *Timer

NewTimer 创建一个新的计时器

func NewTimerWithTraceId

func NewTimerWithTraceId(traceId string) *Timer

NewTimerWithTraceId 创建一个带有自定义跟踪Id的新计时器

func (*Timer) Finish

func (t *Timer) Finish()

Finish 停止计时器

func (*Timer) GetDuration

func (t *Timer) GetDuration() time.Duration

GetDuration 获取计时器的实际持续时间

func (*Timer) GetEndTime

func (t *Timer) GetEndTime() time.Time

GetEndTime 获取计时器的结束时间

func (*Timer) GetPauseDuration

func (t *Timer) GetPauseDuration() time.Duration

GetPauseDuration 获取计时器的暂停持续时间

func (*Timer) GetPaused

func (t *Timer) GetPaused() bool

GetPaused 获取计时器的暂停状态

func (*Timer) GetStartTime

func (t *Timer) GetStartTime() time.Time

GetStartTime 获取计时器开始时间

func (*Timer) GetTimeOut

func (t *Timer) GetTimeOut() time.Duration

GetTimeOut 获取计时器的超时时间

func (*Timer) GetTraceId

func (t *Timer) GetTraceId() string

GetTraceId 获取计时器的跟踪Id

func (*Timer) Pause

func (t *Timer) Pause()

Pause 暂停计时器

func (*Timer) Resume

func (t *Timer) Resume()

Resume 恢复计时器

func (*Timer) Run

func (t *Timer) Run()

Run 启动计时器,开始计时并打印时差

func (*Timer) SetLogPrefix

func (t *Timer) SetLogPrefix(prefix string) *Timer

SetLogPrefix 设置日志前缀

func (*Timer) SetTimeOut

func (t *Timer) SetTimeOut(timeout time.Duration) *Timer

SetTimeOut 设置计时器的超时时间

func (*Timer) SetTraceId

func (t *Timer) SetTraceId(traceId string) *Timer

SetTraceId 设置计时器的跟踪Id

type TimerInterface

type TimerInterface interface {
	Run()                       // 启动计时器
	Pause()                     // 暂停计时器
	Resume()                    // 恢复计时器
	Finish()                    // 完成停止计时器
	GetTraceId() string         // 获取跟踪ID
	GetStartTime() time.Time    // 获取开始时间
	GetEndTime() time.Time      // 获取结束时间
	GetDuration() time.Duration // 获取持续时间
}

TimerInterface 定义计时器的接口

type Unit

type Unit uint8

Unit 时间单位

const (
	UnitNanosecond Unit = iota
	UnitMicrosecond
	UnitMillisecond
	UnitSecond
	UnitMinute
	UnitHour
	UnitDay
	UnitWeek
	UnitMonth
	UnitQuarter
	UnitYear
)

支持的时间单位

func (Unit) String

func (u Unit) String() string

String 返回单位名称

Jump to

Keyboard shortcuts

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