随笔 - 109  文章 - 0  评论 - 2  阅读 - 73876

go 时间范围取日期值

应用场景,如按时间范围查es数据,需要将日期的索引传入,则需要将日期出

//时间范围转换并加上索引名
func (s *SearchEs) GetTime(startTime,endTime,indexName string)  []string  {
	var d []string
	timeFormatTpl := "2006.01.02 15:04:05"
	if len(timeFormatTpl) != len(startTime) {
		timeFormatTpl = timeFormatTpl[0:len(startTime)]
	}
	fmt.Println("时间转换前的开始时间,",startTime)
	fmt.Println("时间转换前的开始时间,",endTime)
	date, err := time.Parse(timeFormatTpl, startTime)
	if err != nil {
		// 时间解析,异常
		fmt.Println("时间解析异常,",err)
		return d
	}
	date2, err := time.Parse(timeFormatTpl, endTime)
	if err != nil {
		// 时间解析,异常
		fmt.Println("时间解析异常,",err)
		return d
	}
	if date2.Before(date) {
		// 如果结束时间小于开始时间,异常
		return d
	}
	// 输出日期格式固定
	timeFormatTpl = "2006.01.02"
	date2Str := date2.Format(timeFormatTpl)
	d = append(d, indexName + "-" + date.Format(timeFormatTpl))
	for {
		if date2Str == date.Format(timeFormatTpl){
			break
		}
		fmt.Println("循环这里")
		date = date.AddDate(0, 0, 1)
		dateStr := date.Format(timeFormatTpl)
		d = append(d, indexName + "-" + dateStr)
		if dateStr == date2Str {
			break
		}
	}
	fmt.Println(d)
	return d

}

es查询需要按照传入的时间范围查询,转化成timestamp的格式

//将时间转换成timestamp,用来排序
func (s *SearchEs) ToTimestamp(args ...string) []string {
	var d []string
	timeFormatTpl := "2006.01.02 15:04:05"
	local,_ := time.LoadLocation("Local")
	//timestamp格式 "2006-01-02T15:04:05.000Z"
	loc2,_ := time.LoadLocation("")
	for _,v:= range args{
		date, _ := time.ParseInLocation(timeFormatTpl,v,local)
		date = date.In(loc2)
		datestr := date.Format(time.RFC3339)
		d = append(d,datestr)
	}
	return d
}
posted on   每天进步一点点点点点  阅读(85)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示