You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
83 lines
2.2 KiB
83 lines
2.2 KiB
package date
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
)
|
|
|
|
// Format 根据特定格式格式化日期
|
|
func (td *DateTime) Format(date time.Time, format string) (string, error) {
|
|
if _, ok := formatMap[format]; !ok {
|
|
return "", errors.New("unsupported format")
|
|
}
|
|
return date.Format(formatMap[format]), nil
|
|
}
|
|
|
|
// Parse 将日期字符串转换为Time
|
|
func (td *DateTime) Parse(dateStr, format string) (time.Time, error) {
|
|
if _, ok := formatMap[format]; !ok {
|
|
return time.Time{}, errors.New("unsupported format")
|
|
}
|
|
return time.Parse(formatMap[format], dateStr)
|
|
}
|
|
|
|
// Offset 时间偏移
|
|
func (td *DateTime) Offset(date time.Time, format string) (time.Time, error) {
|
|
pd, err := time.ParseDuration(format)
|
|
if err != nil {
|
|
return date, err
|
|
}
|
|
return date.Add(pd), nil
|
|
}
|
|
|
|
// OffsetDay 时间日期偏移
|
|
func (td *DateTime) OffsetDay(date time.Time, day int) (time.Time, error) {
|
|
return td.Offset(date, fmt.Sprintf("%dh", day*24))
|
|
}
|
|
|
|
// OffsetHour 按小时偏移
|
|
func (td *DateTime) OffsetHour(date time.Time, hour int) (time.Time, error) {
|
|
return td.Offset(date, fmt.Sprintf("%dh", hour))
|
|
}
|
|
|
|
// OffsetMinute 按分钟偏移
|
|
func (td *DateTime) OffsetMinute(date time.Time, minute int) (time.Time, error) {
|
|
return td.Offset(date, fmt.Sprintf("%dm", minute))
|
|
}
|
|
|
|
// OffsetSecond 按秒偏移
|
|
func (td *DateTime) OffsetSecond(date time.Time, second int) (time.Time, error) {
|
|
return td.Offset(date, fmt.Sprintf("%ds", second))
|
|
}
|
|
|
|
// OffsetMillisecond 按毫秒偏移
|
|
func (td *DateTime) OffsetMillisecond(date time.Time, ms int) (time.Time, error) {
|
|
return td.Offset(date, fmt.Sprintf("%dms", ms))
|
|
}
|
|
|
|
// SubDays 日期差
|
|
func (td *DateTime) SubDays(date1, date2 time.Time) int {
|
|
return int(date1.Sub(date2).Hours() / 24)
|
|
}
|
|
|
|
// SubHours 小时差
|
|
func (td *DateTime) SubHours(date1, date2 time.Time) int {
|
|
return int(date1.Sub(date2).Hours())
|
|
}
|
|
|
|
// SubMinutes 分钟差
|
|
func (td *DateTime) SubMinutes(date1, date2 time.Time) int {
|
|
return int(date1.Sub(date2).Minutes())
|
|
}
|
|
|
|
// SubSeconds 秒差
|
|
func (td *DateTime) SubSeconds(date1, date2 time.Time) int {
|
|
return int(date1.Sub(date2).Seconds())
|
|
}
|
|
|
|
// SubMilliseconds 毫秒差
|
|
func (td *DateTime) SubMilliseconds(date1, date2 time.Time) int {
|
|
return int(date1.Sub(date2).Milliseconds())
|
|
}
|