Files
copier/copier_time_test.go
T
2025-09-28 16:16:30 +08:00

88 lines
1.9 KiB
Go

package copier_test
import (
"encoding/json"
"fmt"
"testing"
"time"
"git.charlienet.top/go/copier"
)
type MyString string
type MyTime time.Time
func TestTime(t *testing.T) {
// 示例1:为内置字符串类型设置时间格式
now := time.Now()
var str string
copier.Copy(&str, now, copier.WithStringTimeFormat("2006-01-02 15:04:05"))
fmt.Printf("时间转字符串: %s\n", str)
// 示例2:为自定义字符串类型设置时间格式
var myStr MyString
copier.Copy(&myStr, now, copier.WithTimeFormat(MyString(""), "2006/01/02"))
fmt.Printf("时间转自定义字符串: %s\n", myStr)
// 示例3:设置默认时间格式
var str1 string
copier.Copy(&str1, now, copier.WithTimeFormat(MyString(""), "2006/01/02"))
fmt.Printf("默认格式: %s\n", str1)
// 示例5:字符串转时间
timeStr := "2023-12-25 10:30:00"
var parsedTime time.Time
copier.Copy(&parsedTime, timeStr,
copier.WithStringTimeFormat("2006-01-02 15:04:05"),
copier.WithTimeFormat(MyString(""), "2006/01/02"),
copier.WithDefaultTimeFormat(time.RFC3339))
fmt.Printf("字符串转时间: %v\n", parsedTime)
}
func TestTimeStruct(t *testing.T) {
type User struct {
Name string
CreatedAt *time.Time
}
src := map[string]any{
"Name": "John",
"CreatedAt": "2023-01-01T10:00:00Z",
}
var user User
if err := copier.Copy(&user, src, copier.WithStringTimeFormat(time.RFC3339)); err != nil {
fmt.Printf("错误: %v\n", err)
} else {
fmt.Printf("用户: %+v\n", user)
b, _ := json.Marshal(user)
t.Log(string(b))
}
// user.CreatedAt
}
func TestFieldTag(t *testing.T) {
type User struct {
Name string
CreatedAt time.Time `copier:"format=2006-01-02 15:04:05"`
}
type User2 struct {
Name string
CreatedAt string
}
var src = User{
Name: "John",
CreatedAt: time.Now(),
}
var dst User2
if err := copier.Copy(&dst, src); err != nil {
fmt.Printf("错误: %v\n", err)
} else {
fmt.Printf("用户: %+v\n", dst)
}
}