feat: time util

This commit is contained in:
Bobo
2025-05-29 00:07:27 +08:00
parent 3ec9bbbd27
commit ace6bd4237
5 changed files with 60 additions and 3 deletions

View File

@@ -42,11 +42,15 @@ var TimestamppbToTimeConverter = copier.TypeConverter{
},
}
func TimeToString(tm *time.Time) *string {
return timeutil.TimeToString(tm, timeutil.ISO8601)
}
func NewTimeStringConverterPair() []copier.TypeConverter {
srcType := &time.Time{}
dstType := trans.Ptr("")
fromFn := timeutil.TimeToTimeString
fromFn := TimeToString
toFn := timeutil.StringTimeToTime
return NewGenericTypeConverterPair(srcType, dstType, fromFn, toFn)

View File

@@ -6,7 +6,7 @@ toolchain go1.24.3
require (
github.com/jinzhu/copier v0.4.0
github.com/tx7do/go-utils v1.1.24
github.com/tx7do/go-utils v1.1.25
)
require (

View File

@@ -1,4 +1,4 @@
git tag v1.1.26
git tag v1.1.27
git tag bank_card/v1.1.5
git tag geoip/v1.1.5

View File

@@ -172,6 +172,25 @@ func TimeToDateString(tm *time.Time) *string {
return trans.String(tm.In(GetDefaultTimeLocation()).Format(DateLayout))
}
func StringToTime(str *string, layout string) *time.Time {
if str == nil {
return nil
}
if len(*str) == 0 {
return nil
}
var err error
var theTime time.Time
theTime, err = time.ParseInLocation(layout, *str, GetDefaultTimeLocation())
if err == nil {
return &theTime
}
return nil
}
func TimeToString(tm *time.Time, layout string) *string {
if tm == nil {
return nil

View File

@@ -156,6 +156,40 @@ func TestTimeToString(t *testing.T) {
fmt.Println(*TimeToString(&now, ISO8601))
fmt.Println(*TimeToString(&now, ISO8601TZHour))
fmt.Println(*TimeToString(&now, ISO8601NoTZ))
layout := "2006-01-02"
expected := now.Format(layout)
result := TimeToString(&now, layout)
assert.NotNil(t, result)
assert.Equal(t, expected, *result)
// 测试空输入
result = TimeToString(nil, layout)
assert.Nil(t, result)
}
func TestStringToTime(t *testing.T) {
// 测试有效时间字符串输入
input := "2023-03-09 12:34:56"
layout := "2006-01-02 15:04:05"
expected := time.Date(2023, 3, 9, 12, 34, 56, 0, GetDefaultTimeLocation())
result := StringToTime(&input, layout)
assert.NotNil(t, result)
assert.Equal(t, expected, *result)
// 测试无效时间字符串输入
invalidInput := "invalid-date"
result = StringToTime(&invalidInput, layout)
assert.Nil(t, result)
// 测试空字符串输入
emptyInput := ""
result = StringToTime(&emptyInput, layout)
assert.Nil(t, result)
// 测试空指针输入
result = StringToTime(nil, layout)
assert.Nil(t, result)
}
func TestTimestamppbToTime(t *testing.T) {