timezone

package
v0.14.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 31, 2026 License: MIT Imports: 3 Imported by: 0

Documentation

Overview

Package timezone 提供"数据库存 UTC、前端展示北京时间"约定的通用时区工具。

多个中国区项目共用同一约定:时间以 UTC 写入数据库,对外展示时转换为 北京时间(Asia/Shanghai)。本包封装该约定下的格式化与解析能力, 并通过 Formatter 支持调用方注入业务专属的时间字段集合,避免全局可变状态。

Index

Constants

View Source
const DateTimeFormat = "2006-01-02 15:04:05"

DateTimeFormat 标准日期时间格式

Variables

View Source
var Shanghai *time.Location

Shanghai 北京时间时区。系统缺失 tzdata 时回退为固定东八区偏移。

Functions

func FormatShanghai

func FormatShanghai(t time.Time) string

FormatShanghai 将 time.Time(按 UTC 解析)格式化为北京时间字符串。

参数:

  • t: 时间值

返回值:

  • string: 北京时间字符串;零值返回空字符串

func NowUTCString

func NowUTCString() string

NowUTCString 返回当前 UTC 时间的标准字符串表示,用于写入数据库的时间字段。

返回值:

  • string: UTC 时间字符串,格式为 2006-01-02 15:04:05

func ParseUTCString

func ParseUTCString(s string) (time.Time, error)

ParseUTCString 将时间字符串解析为 time.Time。 优先按 UTC 解析,失败时回退到服务器本地时区,兼容历史本地时间数据。

参数:

  • s: 时间字符串

返回值:

  • time.Time: 解析后的时间
  • error: 所有 layout 均解析失败时返回错误

func UTCStringToShanghai

func UTCStringToShanghai(s string) string

UTCStringToShanghai 将 UTC 时间字符串转换为北京时间字符串。 输入为空或解析失败时原样返回,避免覆盖非标准字段。

参数:

  • s: UTC 时间字符串

返回值:

  • string: 北京时间字符串;解析失败时返回原值

Types

type Formatter

type Formatter struct {
	Location     *time.Location
	ParseLayouts []string
	// contains filtered or unexported fields
}

Formatter 时区格式化器。时间字段集合与解析 layout 由调用方注入,避免全局可变状态。

func NewFormatter

func NewFormatter(extraFields ...string) *Formatter

NewFormatter 创建 Formatter;extraFields 为业务追加的时间字段名。

func (*Formatter) AddTimeFields

func (f *Formatter) AddTimeFields(keys ...string)

AddTimeFields 向当前 Formatter 追加时间字段名(仅修改当前实例,不影响其他实例)。

func (*Formatter) FormatShanghai

func (f *Formatter) FormatShanghai(t time.Time) string

FormatShanghai 将 time.Time 格式化为北京时间字符串;零值返回空字符串。

func (*Formatter) FormatValue

func (f *Formatter) FormatValue(val interface{}) (string, bool)

FormatValue 处理单个时间值(time.Time 或时间字符串),统一转换为北京时间字符串。 供响应中间件的 Options.FormatTime 注入使用。

参数:

  • val: 原始字段值,支持 time.Time 或时间字符串

返回值:

  • string: 格式化后的北京时间字符串
  • bool: 是否成功识别并格式化

func (*Formatter) IsTimeField

func (f *Formatter) IsTimeField(key string) bool

IsTimeField 判断字段名是否需做时区格式化。

func (*Formatter) ToShanghaiString

func (f *Formatter) ToShanghaiString(s string) string

ToShanghaiString 将 UTC 时间字符串转为北京时间字符串;空/解析失败原样返回。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL