数据清洗:Golang规范日期格式

在做数据导入的时候,由于输入人员多和随意(大多数是审美不同),导致数据格式五花八门,就一个日期列,就会出现下面这些样式的:

  • 2023.02.03
  • 2023/02/03
  • 2023.2.3
  • 2023/2/3
  • 2023年2月3日
  • 2023年2月3日上午
  • 2023-02-03

大体就这么多样式,跟多的,就是中间有些空格。

为了达到统一的数据美,需要一个函数,把所有样式的,都统一成 2023-02-03 这样的。

func HandleData(date string) string {
	date = strings.TrimSpace(date)
	date = strings.ReplaceAll(date, ".", "-")
	date = strings.ReplaceAll(date, "/", "-")
	date = strings.ReplaceAll(date, "年", "-")
	date = strings.ReplaceAll(date, "月", "-")
	date = strings.ReplaceAll(date, "日", "")
	date = strings.ReplaceAll(date, "上午", "")
	date = strings.ReplaceAll(date, "下午", "")

	year := date[0:4]
	tmp := date[5:]
	m := tmp[:strings.Index(tmp, "-")]
	d := tmp[strings.Index(tmp, "-")+1:]
	// fmt.Println(year, m, d)

	m = strings.ReplaceAll(m, " ", "")
	d = strings.ReplaceAll(d, " ", "")
	if len(m) == 1 {
		m = "0" + m
	}
	if len(d) == 1 {
		d = "0" + d
	}
	return year + "-" + m + "-" + d
}

你可能感兴趣的:(golang,开发语言,后端)