golang处理Unix时间戳与JSON时间转换插件库epoch的使用

Golang处理Unix时间戳与JSON时间转换插件库epoch的使用

epoch是一个用于在Golang中处理Unix时间戳与JSON时间转换的库,它提供了将Unix时间戳(秒/毫秒)与内置的time.Time类型相互转换的功能。

安装

go get github.com/vtopc/epoch@latest

功能特性

epoch库提供了以下几种时间类型:

Seconds

处理以秒为单位的Unix时间戳,例如:

{"timestamp":1136239445}

Milliseconds

处理以毫秒为单位的Unix时间戳,例如:

{"timestamp":1136239445999}

StrSeconds

处理字符串格式的秒级Unix时间戳,例如:

{"timestamp":"1136239445"}

StrMilliseconds

处理字符串格式的毫秒级Unix时间戳,例如:

{"timestamp":"1136239445999"}

FloatMS

处理浮点数格式的时间戳,整数部分表示秒,小数部分表示毫秒,例如:

{"timestamp":1136239445.999}

使用示例

基本使用示例

package main

import (
	"encoding/json"
	"fmt"

	"github.com/vtopc/epoch"
)

type Request struct {
	Timestamp epoch.Seconds `json:"timestamp"`
}

func main() {
	var v Request
	err := json.Unmarshal([]byte(`{"timestamp":1136239445}`), &v)
	if err != nil {
		panic(err)
	}

	fmt.Printf("%+v\n", v)
	// 输出: {Timestamp:2006-01-03 00:04:05 +0200 EET}

	// 由于epoch.Seconds继承了time.Time的所有方法,可以这样使用:
	fmt.Println(v.Timestamp.Year())
	// 输出: 2006
	fmt.Println(v.Timestamp.UTC().String())
	// 输出: 2006-01-02 22:04:05 +0000 UTC
}

毫秒级时间戳处理示例

package main

import (
	"encoding/json"
	"fmt"

	"github.com/vtopc/epoch"
)

type Request struct {
	Timestamp epoch.Milliseconds `json:"timestamp"`
}

func main() {
	var v Request
	err := json.Unmarshal([]byte(`{"timestamp":1136239445999}`), &v)
	if err != nil {
		panic(err)
	}

	fmt.Printf("%+v\n", v)
	// 输出毫秒级时间戳转换后的时间
}

字符串格式时间戳处理示例

package main

import (
	"encoding/json"
	"fmt"

	"github.com/vtopc/epoch"
)

type Request struct {
	Timestamp epoch.StrSeconds `json:"timestamp"`
}

func main() {
	var v Request
	err := json.Unmarshal([]byte(`{"timestamp":"1136239445"}`), &v)
	if err != nil {
		panic(err)
	}

	fmt.Printf("%+v\n", v)
	// 输出字符串格式秒级时间戳转换后的时间
}

注意事项

  1. epoch库中的所有类型都继承了内置的time.Time类型,因此可以使用time.Time的所有方法
  2. 每种类型都有自定义的序列化和反序列化方法,用于在JSON和time.Time之间转换
  3. 根据时间戳的格式(秒/毫秒,整数/字符串)选择合适的类型

这个库简化了Golang中Unix时间戳与JSON之间的转换工作,特别适合处理各种格式的API时间戳数据。


更多关于golang处理Unix时间戳与JSON时间转换插件库epoch的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于golang处理Unix时间戳与JSON时间转换插件库epoch的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


Golang中Unix时间戳与JSON时间转换:epoch库使用指南

在Golang中处理Unix时间戳与JSON时间格式的转换是一个常见需求,epoch库为此提供了简洁高效的解决方案。下面我将详细介绍如何使用这个库。

安装epoch库

首先安装epoch库:

go get github.com/vtopc/epoch

基本使用方法

1. 时间戳与time.Time互转

package main

import (
	"fmt"
	"time"
	"github.com/vtopc/epoch"
)

func main() {
	// 当前时间转Unix时间戳(秒)
	now := time.Now()
	unixSec := epoch.Unix(now)
	fmt.Printf("Unix秒级时间戳: %d\n", unixSec)

	// Unix时间戳转time.Time
	t := epoch.Time(unixSec)
	fmt.Printf("转换回时间: %v\n", t)

	// 毫秒级时间戳处理
	unixMilli := epoch.UnixMilli(now)
	fmt.Printf("Unix毫秒级时间戳: %d\n", unixMilli)
	
	tFromMilli := epoch.TimeMilli(unixMilli)
	fmt.Printf("从毫秒转换回时间: %v\n", tFromMilli)
}

2. JSON序列化与反序列化

package main

import (
	"encoding/json"
	"fmt"
	"time"
	"github.com/vtopc/epoch"
)

type Event struct {
	ID        int       `json:"id"`
	Name      string    `json:"name"`
	CreatedAt epoch.Time `json:"created_at"` // 使用epoch.Time类型
}

func main() {
	// 序列化为JSON(时间会转为Unix时间戳)
	event := Event{
		ID:        1,
		Name:      "Test Event",
		CreatedAt: epoch.Time(time.Now().Unix()),
	}
	
	jsonData, err := json.Marshal(event)
	if err != nil {
		panic(err)
	}
	fmt.Printf("JSON数据: %s\n", jsonData)

	// 从JSON反序列化
	var newEvent Event
	err = json.Unmarshal(jsonData, &newEvent)
	if err != nil {
		panic(err)
	}
	fmt.Printf("反序列化后的时间: %v\n", time.Time(newEvent.CreatedAt))
}

3. 处理毫秒级时间戳

package main

import (
	"encoding/json"
	"fmt"
	"time"
	"github.com/vtopc/epoch"
)

type LogEntry struct {
	Message   string           `json:"message"`
	Timestamp epoch.MilliTime  `json:"timestamp"` // 使用毫秒级时间戳
}

func main() {
	// 创建并序列化
	entry := LogEntry{
		Message:   "System started",
		Timestamp: epoch.MilliTime(time.Now().UnixNano() / int64(time.Millisecond)),
	}
	
	data, err := json.Marshal(entry)
	if err != nil {
		panic(err)
	}
	fmt.Printf("日志JSON: %s\n", data)

	// 反序列化
	var newEntry LogEntry
	err = json.Unmarshal(data, &newEntry)
	if err != nil {
		panic(err)
	}
	fmt.Printf("日志时间: %v\n", time.Time(newEntry.Timestamp))
}

高级用法

自定义时间格式

package main

import (
	"encoding/json"
	"fmt"
	"time"
	"github.com/vtopc/epoch"
)

// 自定义时间类型,实现json.Marshaler和json.Unmarshaler接口
type CustomTime struct {
	epoch.Time
}

func (ct CustomTime) MarshalJSON() ([]byte, error) {
	return json.Marshal(time.Time(ct.Time).Format("2006-01-02 15:04:05"))
}

func (ct *CustomTime) UnmarshalJSON(data []byte) error {
	var s string
	if err := json.Unmarshal(data, &s); err != nil {
		return err
	}
	t, err := time.Parse("2006-01-02 15:04:05", s)
	if err != nil {
		return err
	}
	ct.Time = epoch.Time(t.Unix())
	return nil
}

type Project struct {
	Name      string     `json:"name"`
	StartDate CustomTime `json:"start_date"`
}

func main() {
	project := Project{
		Name:      "Epoch Demo",
		StartDate: CustomTime{epoch.Time(time.Now().Unix())},
	}
	
	data, _ := json.Marshal(project)
	fmt.Printf("项目JSON: %s\n", data)
}

性能考虑

epoch库相比直接使用time.Time有以下优势:

  1. JSON数据更小(传输时间戳比RFC3339字符串更紧凑)
  2. 序列化/反序列化更快(无需解析时间字符串格式)
  3. 与JavaScript等前端语言互操作性更好(前端也常用Unix时间戳)

注意事项

  1. 确保前后端对时间戳精度(秒/毫秒)理解一致
  2. 处理时区问题:epoch库默认使用UTC时间
  3. 对于需要人类可读的场景,可能需要额外处理

希望这个指南能帮助你在Golang项目中高效处理时间戳与JSON时间的转换!

回到顶部