当前位置: 首页 > article >正文

GO Date数据处理

今天封装了一个go 的date数据处理,方便以后直接用
1、创建dateformat.go文件

package model

import (
	"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 model

import (
	"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)
	}
}


http://www.kler.cn/a/284309.html

相关文章:

  • 离线部署maven项目笔记(2)
  • 【编程概念基础知识】
  • 面试经典 150 题:121,125
  • python的包引入
  • 《深入浅出HTTPS​​​​​​​​》读书笔记(8):密码学Hash算法的分类
  • 使用SearXNG-搭建个人搜索引擎(附国内可用Docker镜像源)
  • Python知识点:如何使用Selenium进行自动化Web测试
  • python-矩阵交换行
  • AI学习指南深度学习篇-长短时记忆网络python实践
  • 使用uniapp制作录音功能(VUE3)
  • 鸿蒙OS试题(4)
  • DSP48E2使用以及FIR滤波器定点设计实现与优化
  • 小琳AI课堂:生成对抗网络(GANs)
  • HarmonyOS开发实战( Beta5版)Web组件开发性能提升指导
  • 处理.NET Core中的时区转换问题
  • 帕金森患者在运动时有哪些类型的运动推荐?
  • SpringWeb后端开发-登录认证
  • CSS中的`z-index`属性是如何工作(注意事项)
  • (苍穹外卖)day03菜品管理
  • 5Kg负重30分钟长航时多旋翼无人机详解
  • MySQL简介和管理
  • 为什么我的手机卡需要快递员给激活?这到底安全吗?
  • Web攻击-XSS、CSRF、SQL注入
  • SimpleTranslationAIAgent:基于C#与LLM的翻译AI Agent
  • 国产游戏行业的技术进步与未来展望
  • Java | Leetcode Java题解之第385题迷你语法分析器