代码拉取完成,页面将自动刷新
package lang
import (
"strings"
"sync"
"time"
)
const (
FormatDate = "yyyy-MM-dd"
FormatTime = "HH:mm:ss"
FormatDatetime = FormatDate + " " + FormatTime
)
// DateFormat 函数用于将时间格式化为指定的字符串格式
func DateFormat(t time.Time, format string) string {
// 将自定义的格式字符串转换为 Go 的时间格式字符串
layout := convertToGoLayout(format)
return t.Format(layout)
}
// DateParse 函数用于解析指定格式的日期字符串
func DateParse(dateStr string, format string) (time.Time, error) {
// 将自定义的格式字符串转换为 Go 的时间格式字符串
layout := convertToGoLayout(format)
return time.Parse(layout, dateStr)
}
type Date struct {
time time.Time
lock sync.RWMutex
}
func DateNow() *Date {
return &Date{
time: time.Now(),
}
}
func DateNew(time time.Time) *Date {
return &Date{
time: time,
}
}
// DateStr
// time: 时间 eg: 2024-14-12 12:15:20
// format: 时间格式 eg: yyyy-MM-dd HH:mm:ss OR FormatDatetime
func DateStr(time string, format string) (*Date, error) {
parse, err := DateParse(time, format)
if err != nil {
return nil, err
}
return &Date{
time: parse,
}, nil
}
func (t *Date) ToString(format string) string {
return DateFormat(t.time, format)
}
// OffsetYear 函数增加或减少指定的年数
func (t *Date) OffsetYear(offset int) *Date {
t.lock.Lock()
defer t.lock.Unlock()
t.time = t.time.AddDate(offset, 0, 0)
return t
}
// OffsetMonth 函数增加或减少指定的月数
func (t *Date) OffsetMonth(offset int) *Date {
t.lock.Lock()
defer t.lock.Unlock()
t.time = t.time.AddDate(0, offset, 0)
return t
}
// OffsetDay 函数增加或减少指定的天数
func (t *Date) OffsetDay(offset int) *Date {
t.lock.Lock()
defer t.lock.Unlock()
t.time = t.time.AddDate(0, 0, offset)
return t
}
// OffsetHour 函数增加或减少指定的小时数
func (t *Date) OffsetHour(offset int) *Date {
t.lock.Lock()
defer t.lock.Unlock()
t.time = t.time.Add(time.Duration(offset) * time.Hour)
return t
}
// OffsetMinute 函数增加或减少指定的分钟数
func (t *Date) OffsetMinute(offset int) *Date {
t.lock.Lock()
defer t.lock.Unlock()
t.time = t.time.Add(time.Duration(offset) * time.Minute)
return t
}
// OffsetSecond 函数增加或减少指定的秒数
func (t *Date) OffsetSecond(offset int) *Date {
t.lock.Lock()
defer t.lock.Unlock()
t.time = t.time.Add(time.Duration(offset) * time.Second)
return t
}
func (t *Date) CompareTimes(time time.Time) int {
t.lock.RLock()
defer t.lock.RUnlock()
if t.time.Before(time) {
return -1
} else if t.time.After(time) {
return 1
} else if t.time.Equal(time) {
return 0
}
panic("time compare unreachable")
}
// convertToGoLayout 函数将自定义的日期格式转换为 Go 的时间格式
func convertToGoLayout(format string) string {
// 替换自定义格式为 Go 的时间格式
layout := format
layout = strings.Replace(layout, "yyyy", "2006", -1)
layout = strings.Replace(layout, "MM", "01", -1)
layout = strings.Replace(layout, "dd", "02", -1)
layout = strings.Replace(layout, "HH", "15", -1)
layout = strings.Replace(layout, "hh", "03", -1)
layout = strings.Replace(layout, "mm", "04", -1)
layout = strings.Replace(layout, "ss", "05", -1)
return layout
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。