et-go 20240919重建
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

77 lines
2.3 KiB

package kafka
import (
"encoding/json"
"fmt"
"testing"
"time"
)
func TestAggDataHandler_HandleMessage(t *testing.T) {
h := AggDataHandler{}
aggDataMsg := `
{"date":"2024-09-19T09:39:59.999+0800","sensorId":106,"structId":1,"factorId":11,"aggTypeId":2006,"aggMethodId":3004,"agg":{"strain":-19.399999618530273},"changed":{"strain":-3}}
`
h.HandleMessage(aggDataMsg)
}
func TestFormatTime(t *testing.T) {
now := time.Now()
nowWithSecond := now.Truncate(time.Second)
fmt.Println(nowWithSecond)
fmt.Println("nowWithSecond.UnixMilli", nowWithSecond.UnixMilli())
fmt.Println(nowWithSecond.Nanosecond())
fmt.Println(nowWithSecond.Second())
nowWithMill := nowWithSecond.Add(time.Millisecond)
fmt.Println(nowWithMill.Nanosecond())
fmt.Printf(" %v\n %v\n %v\n ", now, nowWithSecond, nowWithMill)
// 假设 collectTime 是一个 time.Time 类型的时间变量
collectTime := time.Date(2024, time.December, 1, 16, 30, 0, 123, time.UTC)
fmt.Println("collectTime: ", collectTime)
// 将时间截断到毫秒级别
truncatedTime := collectTime.Truncate(time.Millisecond)
fmt.Println("collectTime truncate millisecond : ", truncatedTime)
// 手动添加毫秒
if truncatedTime.Nanosecond() == 0 {
truncatedTime = truncatedTime.Add(time.Millisecond)
}
fmt.Println("保持毫秒部分为0的时间格式:", truncatedTime)
//自定义的 MarshalJSON 方法来实现,在将 EsTheme 结构体序列化为JSON时,格式化时间的输出格式为 2024-10-01T10:36:10.226+08:00。
now = time.Now()
fmt.Println(now)
theme := ThemeForTest{
CollectTime: collectTime,
Sensor: 0,
CreateTime: now,
}
themeBytes, err := theme.MarshalJSON()
if err != nil {
fmt.Printf("theme序列化异常,err=%s", err.Error())
}
fmt.Println(string(themeBytes))
}
type ThemeForTest struct {
CollectTime time.Time `json:"collect_time"`
Sensor int `json:"sensor"`
CreateTime time.Time `json:"create_time"`
}
func (e ThemeForTest) MarshalJSON() ([]byte, error) {
type Alias ThemeForTest
data := struct {
CollectTime string `json:"collect_time"`
CreateTime string `json:"create_time"`
*Alias
}{
CollectTime: e.CollectTime.Format("2006-01-02T15:04:05.000+08:00"),
CreateTime: e.CreateTime.Format("2006-01-02T15:04:05.000+08:00"),
Alias: (*Alias)(&e),
}
return json.Marshal(&data)
}