今天封装了一个go 的date数据处理,方便以后直接用
1、创建dateformat.go文件
package modelimport ("fmt""time"
)type dateFormatter struct {time.Time
}// ConvertTimeStringToTimestamp 将指定格式的时间字符串转换为 Unix 时间戳
func (u *dateFormatter) ConvertTimeStringToTimestamp(timeString, layout string) (int64, error) {t, err := time.Parse(layout, timeString)if err != nil {return 0, err}return t.Unix(), nil
}// ConvertTimeStringFormat 将时间字符串从一种格式转换为另一种格式
func (u *dateFormatter) ConvertTimeStringFormat(timeString, originalLayout, newLayout string) (string, error) {t, err := time.Parse(originalLayout, timeString)if err != nil {return "", err}return t.Format(newLayout), nil
}// CalculateDateDifference 计算两个日期之间的天数差func (u *dateFormatter) CalculateDateDifference(date1, date2, layout string) (int, error) {d1, err := time.Parse(layout, date1)if err != nil {return 0, err}d2, err := time.Parse(layout, date2)if err != nil {return 0, err}duration := d2.Sub(d1)return int(duration.Hours() / 24), nil
}// AddDaysToDate 为指定日期增加或减少天数
func (u *dateFormatter) AddDaysToDate(date string, days int, layout string) (string, error) {d, err := time.Parse(layout, date)if err != nil {return "", err}newDate := d.Add(time.Duration(days) * 24 * time.Hour)return newDate.Format(layout), nil
}// ConvertTimestampToTimeString 将 Unix 时间戳转换为指定格式的时间字符串
func (u *dateFormatter) ConvertTimestampToTimeString(timestamp int64, layout string) string {t := time.Unix(timestamp, 0)return t.Format(layout)
}// CompareDates 比较两个日期,返回-1(日期1早于日期2),0(日期相等),1(日期1晚于日期2)
func (u *dateFormatter) CompareDates(date1, date2, layout string) (int, error) {d1, err := time.Parse(layout, date1)if err != nil {return 0, err}d2, err := time.Parse(layout, date2)if err != nil {return 0, err}if d1.Before(d2) {return -1, nil}if d1.After(d2) {return 1, nil}return 0, nil
}// ConvertTimeRange 解析并转换时间区间为指定格式或Unix时间戳
func (u *dateFormatter) ConvertTimeRange(startTimeStr, endTimeStr, layout, outputLayout string) (string, string, error) {startTime, err := time.Parse(layout, startTimeStr)if err != nil {return "", "", err}endTime, err := time.Parse(layout, endTimeStr)if err != nil {return "", "", err}if outputLayout == "unix" {// 返回Unix时间戳startUnix := fmt.Sprintf("%d", startTime.Unix())endUnix := fmt.Sprintf("%d", endTime.Unix())return startUnix, endUnix, nil} else {// 返回指定格式的字符串startFormatted := startTime.Format(outputLayout)endFormatted := endTime.Format(outputLayout)return startFormatted, endFormatted, nil}
}// ExtractDateComponents 从字符串日期中提取年、月、日、小时、分钟、秒等数据
func (u *dateFormatter) ExtractDateComponents(dateStr, layout string) (int, int, int, int, int, int, error) {date, err := time.Parse(layout, dateStr)if err != nil {return 0, 0, 0, 0, 0, 0, err}year := date.Year()month := int(date.Month())day := date.Day()hour := date.Hour()minute := date.Minute()second := date.Second()return year, month, day, hour, minute, second, nil
}// ConvertISOToCustomFormat 将ISO时间格式转换为指定的格式
func (u *dateFormatter) ConvertISOToCustomFormat(isoTimeStr, outputLayout string) (string, error) {date, err := time.Parse(time.RFC3339, isoTimeStr)if err != nil {return "", err}return date.Format(outputLayout), nil
}
2、创建单元测试测试文件
dateformat_test.go
package modelimport ("fmt""testing"
)func TestConvertISOWithTimezone(t *testing.T) {isoTimeStr := "2024-08-30T14:00:00+02:00"testData := dateFormatter{}// 转换为自定义格式customFormat, err := testData.ConvertISOToCustomFormat(isoTimeStr, "2006-01-02 15:04:05 MST")if err != nil {fmt.Println("Error converting ISO time:", err)} else {fmt.Println("Converted Time:", customFormat)}// 另一个转换例子:转换为UTC时间格式customUTCFormat, err := testData.ConvertISOToCustomFormat(isoTimeStr, "2006-01-02 15:04:05 UTC")if err != nil {fmt.Println("Error converting ISO time:", err)} else {fmt.Println("Converted UTC Time:", customUTCFormat)}
}
func TestConvertISOToCustomFormat(t *testing.T) {isoTimeStr := "2024-08-30T14:00:00Z"testData := dateFormatter{}// 转换为自定义格式customFormat, err := testData.ConvertISOToCustomFormat(isoTimeStr, "2006-01-02 15:04:05")if err != nil {fmt.Println("Error converting ISO time:", err)} else {fmt.Println("Converted Time:", customFormat)}// 另一个转换例子:只显示日期部分customDateFormat, err := testData.ConvertISOToCustomFormat(isoTimeStr, "2006-01-02")if err != nil {fmt.Println("Error converting ISO time:", err)} else {fmt.Println("Converted Date:", customDateFormat)}
}func TestTimestampToTimeString(t *testing.T) {testData := dateFormatter{}timestamp := int64(1725002400)layout := "2006-01-02 15:04:05"formattedTime := testData.ConvertTimestampToTimeString(timestamp, layout)fmt.Println("Formatted Time:", formattedTime)
}
func TestCalculateDateDifference(t *testing.T) {testData := dateFormatter{}days, err := testData.CalculateDateDifference("2024-08-30", "2024-09-05", "2006-01-02")if err != nil {fmt.Println("Error:", err)} else {fmt.Println("Difference in days:", days)}
}func TestDateFormatMain(t *testing.T) {testData := dateFormatter{}timeString := "2024-08-30 14:00:00"layout := "2006-01-02 15:04:05"timestamp, err := testData.ConvertTimeStringToTimestamp(timeString, layout)if err != nil {fmt.Println("Error converting time string to timestamp:", err)} else {fmt.Println("Unix Timestamp:", timestamp)}
}func TestCompareDates(t *testing.T) {testData := dateFormatter{}result, err := testData.CompareDates("2024-08-30", "2024-09-05", "2006-01-02")if err != nil {fmt.Println("Error:", err)} else {fmt.Println("Comparison Result:", result)}
}func TestAddDaysToDate(t *testing.T) {testData := dateFormatter{}newDate, err := testData.AddDaysToDate("2024-08-30", 10, "2006-01-02")if err != nil {fmt.Println("Error:", err)} else {fmt.Println("New Date:", newDate)}
}
func TestConvertTimeStringFormat(t *testing.T) {originalTimeString := "2024-08-30 14:00:00"originalLayout := "2006-01-02 15:04:05"newLayout := "02-01-2006 03:04 PM"testData := dateFormatter{}newTimeString, err := testData.ConvertTimeStringFormat(originalTimeString, originalLayout, newLayout)if err != nil {fmt.Println("Error converting time string format:", err)} else {fmt.Println("New Formatted Time:", newTimeString)}
}func TestConvertTimeRange(t *testing.T) {// 示例1:将时间区间转换为Unix时间戳testData := dateFormatter{}startUnix, endUnix, err := testData.ConvertTimeRange("2024-08-30 14:00:00", "2024-09-01 18:00:00", "2006-01-02 15:04:05", "unix")if err != nil {fmt.Println("Error:", err)} else {fmt.Println("Start Unix Timestamp:", startUnix)fmt.Println("End Unix Timestamp:", endUnix)}// 示例2:将时间区间转换为新的日期格式startFormatted, endFormatted, err := testData.ConvertTimeRange("2024-08-30 14:00:00", "2024-09-01 18:00:00", "2006-01-02 15:04:05", "02-Jan-2006 03:04 PM")if err != nil {fmt.Println("Error:", err)} else {fmt.Println("Start Formatted Time:", startFormatted)fmt.Println("End Formatted Time:", endFormatted)}
}func TestExtractDateComponents(t *testing.T) {dateStr := "2024-08-30 14:00:00"layout := "2006-01-02 15:04:05"testData := dateFormatter{}year, month, day, hour, minute, second, err := testData.ExtractDateComponents(dateStr, layout)if err != nil {fmt.Println("Error parsing date:", err)} else {fmt.Printf("Year: %d, Month: %d, Day: %d, Hour: %d, Minute: %d, Second: %d\n", year, month, day, hour, minute, second)}
}