Golang字符串转换为日期万能方法,兼容大部分日期时间格式,一键转换。

1551人浏览 2022-04-25

Golang字符串转换为日期万能方法,兼容大部分日期时间格式,一键转换。

工作中遇到一个问题,就是需要读取excle表中的日期,并转换为时间格式处理,由于不能保证用户统一的日期格式,比如2022-01-12 有的输入2022-1-12 在转换为日期的时候非常头疼。于是抽时间封装了以下万能转换方法,可根据需求自定义添加其他layout格式

 

废话少说,上代码:

// ParseDateByDateStr 字符串日期转化为时间戳 例如:"2018-01-01"
func ParseDateByDateStr(defaultLayout, dateStr string) (time.Time, error) {
	resDate := time.Time{}
	if defaultLayout != "" {
		return time.ParseInLocation(defaultLayout, dateStr, time.Local)
	}
	//定义可能出现的日期格式
	var (
		years = []string{
			"2006",
			"06",
		}
		months = []string{
			"01",
			"1",
		}
		days = []string{
			"02",
			"2",
		}
		hours = []string{
			"03",
			"3",
			"15",
		}
		minutes = []string{
			"04",
			"4",
		}
		seconds = []string{
			"05",
			"5",
		}
		splits = []string{
			"-",
			".",
			"/",
		}
	)

	var layouts = make(map[string][]string, 0)

	//匹配日期格式:"2006-01-02"
	for _, year := range years {
		for _, month := range months {
			for _, day := range days {
				for _, split := range splits {
					lastLayout := year + split + month + split + day
					layouts[split] = append(layouts[split], lastLayout)
				}
			}
		}
	}
	//匹配日期格式:"2006-01-02 15:04:05"
	for _, year := range years {
		for _, month := range months {
			for _, day := range days {
				for _, hour := range hours {
					for _, minute := range minutes {
						for _, second := range seconds {
							for _, split := range splits {
								lastLayout := year + split + month + split + day + " " + hour + ":" + minute + ":" + second
								layouts[split] = append(layouts[split], lastLayout)
							}
						}
					}
				}
			}
		}
	}
	//匹配日期格式:"2006-01-02 15:04"
	for _, year := range years {
		for _, month := range months {
			for _, day := range days {
				for _, hour := range hours {
					for _, minute := range minutes {
						for _, split := range splits {
							lastLayout := year + split + month + split + day + " " + hour + ":" + minute
							layouts[split] = append(layouts[split], lastLayout)
						}
					}
				}
			}
		}
	}

	var waitLayouts = make([]string, 0)

	//根据字符串日期格式查找分隔符
	//如果字符串日期格式中包含分隔符,则使用该分隔符 -
	if index := strings.Index(dateStr, "-"); index > -1 {
		waitLayouts = layouts["-"]
	}
	//如果字符串日期格式中包含分隔符,则使用该分隔符 -
	if index := strings.Index(dateStr, "/"); index > -1 {
		waitLayouts = layouts["/"]
	}
	//如果字符串日期格式中包含分隔符,则使用该分隔符 -
	if index := strings.Index(dateStr, "."); index > -1 {
		waitLayouts = layouts["."]
	}
	if len(waitLayouts) > 0 {
		for _, layout := range waitLayouts {
			resDate, err := time.ParseInLocation(layout, dateStr, time.Local)
			if err == nil {
				return resDate, nil
			}
		}
		return resDate, nil
	} else {
		return resDate, errors.New("无可用layout! ")
	}
}

测试使用:

func TestParseDateByDateStr(t *testing.T) {
	date, err := ParseDateByDateStr("", "2022.04.13 13:20")
	if err != nil {
		t.Error("error:", err)
	}

	if date.Year() != 2022 || date.Month() != 4 || date.Day() != 13 {
		t.Error("ParseDateByDateStr error")
	}
	t.Logf("%v", date)
}

 

或者使用dateparse标准库处理

 

推荐文章

GORM 自定义结构体关联的数据库表名称和自定义结构体字段对应的数据表字段名
2021-02-23
KChatRoom在线多人聊天室,项目是使用Websocket和Gin框架基于Golang开发的在线聊天室
2021-05-17
Gin框架下获取所有路由信息
2021-07-14
搜索文章