Armadilhas a serem observadas ao converter carimbos de data/hora go, int64 -> float64

Um pequeno problema encontrado no projeto, deixe-me registrar: quando goa biblioteca padrão json.Unmarshalusa um valor do tipo interface{}de recebimento int, ele será convertido para float64.Isso também é razoável. Este artigo não se aprofundará na jsonimplementação da biblioteca.

Ao utilizar diretamente interface{}para receber parâmetros, seus tipos não serão convertidos, conforme segue:

func tInterfaceTimestamp() {
    
    
	nowTimestamp := time.Now().Unix()
	fmt.Println("当前时间戳秒:", nowTimestamp)

	var i interface{
    
    } = nowTimestamp
	fmt.Println(reflect.TypeOf(i))
}

A saída é a seguinte:

当前时间戳秒: 1636619064
int64

Mas quando usamos jsonpara fazer uma conversão, descobrimos que int64foi convertido em float64, da seguinte forma:

func tJsonTimestamp() {
    
    
	type test struct {
    
    
		Timestamp int64
	}
	var data = test{
    
    time.Now().Unix()}
	buf, _ := json.Marshal(data)

	var data2 = struct{
    
     Timestamp interface{
    
    } }{
    
    }
	json.Unmarshal(buf, &data2)
	fmt.Println(reflect.TypeOf(data2.Timestamp))

	var resMap = make(map[string]interface{
    
    })
	if er := json.Unmarshal(buf, &resMap); er != nil {
    
    
		fmt.Println(er)
		return
	}

	t, ok := resMap["Timestamp"]
	if !ok {
    
    
		return
	}

	fmt.Println(reflect.TypeOf(t))
}

Saída:

float64
float64

A propósito, aqui está um pequeno método para converter carimbos de data/hora em stringstrings, com precisão de segundos.

func GetTimestampStr(ts int64) string {
    
    
	sLength := 10 // 以秒来做精度
	str := strconv.FormatInt(ts, 10)
	tsLength := len(str)
	if tsLength < sLength {
    
    
		fmt.Println("====== 时间戳小于10啦:", ts)
		return ""
	}

	multiple := tsLength - sLength
	if multiple > 0 {
    
    
		ts = ts / (int64(math.Pow10(multiple)))
	}
	// 这里不用考虑时区,时间戳会根据当前操作系统的时区进行转换
	return time.Unix(ts, 0).Format("2006-01-02 15:04:05")
}

Todos os códigos acima estão no meu repositório Gitee/pacote timeTest . O repositório também contém alguns códigos de teste diários, etc. Se você estiver interessado, pode dar uma olhada.

おすすめ

転載: blog.csdn.net/DisMisPres/article/details/121270333