feat(timex): 自 go-hua/common 迁入时间日期工具并独立成包
- NT/UTC 时间戳互转、时间字符串转毫秒时间戳、指定年月天数 - 附单元测试、examples/timex 例程与包 README
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
// Package timex 时间与日期工具:Windows NT 时间戳与 Unix 时间戳互转、
|
||||
// 时间字符串转毫秒时间戳、查询指定年月的天数。
|
||||
package timex
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// NtToUtc Windows NT timestamp to Unix UTC timestamp
|
||||
func NtToUtc(ntTimestamp uint64) uint64 {
|
||||
unixTimestamp := (ntTimestamp - 11644473600000000) / 1000000
|
||||
return unixTimestamp
|
||||
}
|
||||
|
||||
// UtcToNt Unix UTC timestamp to Windows NT timestamp
|
||||
func UtcToNt(unixTime uint64) uint64 {
|
||||
ntTimestamp := unixTime*1000000 + 11644473600000000
|
||||
return ntTimestamp
|
||||
}
|
||||
|
||||
// 时间字符串转时间戳
|
||||
func TimeStrToTimestamp(timeStr string) (int64, error) {
|
||||
layout := "2006-01-02 15:04:05"
|
||||
t, err := time.ParseInLocation(layout, timeStr, time.Local)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
// 获取时间戳(单位是秒),并转换为毫秒
|
||||
millisecondTimestamp := t.UnixMilli()
|
||||
return millisecondTimestamp, nil
|
||||
}
|
||||
|
||||
// GetYearMonthToDay 查询指定年份指定月份有多少天
|
||||
// @params year int 指定年份
|
||||
// @params month int 指定月份
|
||||
func GetYearMonthToDay(year int, month int) int {
|
||||
// 有31天的月份
|
||||
day31 := map[int]bool{
|
||||
1: true,
|
||||
3: true,
|
||||
5: true,
|
||||
7: true,
|
||||
8: true,
|
||||
10: true,
|
||||
12: true,
|
||||
}
|
||||
if day31[month] {
|
||||
return 31
|
||||
}
|
||||
// 有30天的月份
|
||||
day30 := map[int]bool{
|
||||
4: true,
|
||||
6: true,
|
||||
9: true,
|
||||
11: true,
|
||||
}
|
||||
if day30[month] {
|
||||
return 30
|
||||
}
|
||||
// 计算是平年还是闰年
|
||||
if (year%4 == 0 && year%100 != 0) || year%400 == 0 {
|
||||
// 得出2月的天数
|
||||
return 29
|
||||
}
|
||||
// 得出2月的天数
|
||||
return 28
|
||||
}
|
||||
Reference in New Issue
Block a user