tz

package
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Jan 27, 2026 License: MIT Imports: 14 Imported by: 0

README

TimeZone Package

Overview

The tz package provides comprehensive timezone functionality including:

  • Timezone Detection: Automatically detect system timezone on Windows and Unix systems
  • Timezone Conversion: Convert time between different timezones
  • Timezone Lookup: Find timezones by name, country code, or abbreviation
  • Data Management: Load and manage timezone and country data from embedded JSON files

Features

✅ Core Functionality
  • Cross-platform timezone detection (Windows/Unix)
  • Lazy loading of timezone data for performance
  • Caching of timezone locations
  • Comprehensive timezone information
  • Time conversion between timezones
  • DST (Daylight Saving Time) support
✅ Data Sources
  • IANA Timezone Database via tzdata
  • TimeZoneDB.com CSV data
  • Windows Zone Mapping from CLDR
  • Country information with timezone mapping

API Reference

Core Functions
// Get current system timezone location
loc, err := tz.GetLocation()
locStr := tz.GetLocationString()

// Find timezones
tz, found := tz.FindTimeZoneByZoneName("Asia/Shanghai")
timezones, found := tz.FindTimeZonesByCountryCode("CN")
timezones, found := tz.FindTimeZonesByAbbreviation("CST")

// Get timezone information
info, err := tz.GetTimeZoneInfo("Asia/Shanghai")

// Convert time between timezones
converted, err := tz.ConvertTime(time.Now(), "Asia/Shanghai", "America/New_York")

// Check DST
isDST, err := tz.IsDST(time.Now(), "America/New_York")

// Get timezone offset
offset, err := tz.GetOffset("Asia/Shanghai")
Data Access
// Get all data
countries := tz.GetCountries()
timezones := tz.GetTimeZones()

Data Structures

TimeZone
type TimeZone struct {
    ZoneName     string         `json:"zone_name"`
    CountryCode  string         `json:"country_code"`
    Abbreviation string         `json:"abbreviation"`
    GmtOffset    int          `json:"gmt_offset"` // in seconds
    Dst          bool         `json:"dst"`        // daylight saving time
    Location     *time.Location `json:"-"`
}
TimeZoneInfo
type TimeZoneInfo struct {
    Name         string         `json:"name"`
    Country      string         `json:"country"`
    Offset       int            `json:"offset"`       // in seconds
    OffsetString string         `json:"offset_string"` // "+08:00" format
    IsDST        bool          `json:"is_dst"`
    Abbreviation string         `json:"abbreviation"`
    Location     *time.Location `json:"-"`
}

Performance Features

Lazy Loading

Timezone data is loaded only when first accessed to improve startup time.

Caching

Timezone locations are cached to avoid repeated loading from system.

Memory Efficient

Duplicate timezone entries are filtered out during initialization.

Platform Support

Unix/Linux/macOS
  • Reads from /etc/timezone file
  • Falls back to /etc/localtime symlink parsing
  • Default: Asia/Shanghai
Windows
  • Uses tzutil.exe command
  • Maps Windows timezone IDs to IANA timezone names
  • Default: Asia/Shanghai

Build and Data Generation

Generate JSON from CSV
cd tz
go run make.go -generate-json
Clean Generated Files
go run ../../cmd/make/main.go -clean

Error Handling

The package defines standard errors:

  • ErrTimeZoneNotFound: Timezone not found
  • ErrInvalidTimeZone: Invalid timezone format
  • ErrConversionFailed: Timezone conversion failed
  • ErrLocationNotFound: Location not found

Testing

Run tests with:

go test ./...
go test -v ./...

Dependencies

  • Go 1.21+
  • Standard library only (no external dependencies)

File Structure

tz/
├── types.go           # Type definitions and interfaces
├── errors.go          # Error definitions
├── tz.go             # Core functionality
├── tz_unix.go        # Unix-specific implementation
├── tz_windows.go     # Windows-specific implementation
├── time_zone.go       # TimeZone types and data
├── country.go        # Country types and data
├── make.go           # Data generation tool
├── *_test.go         # Test files
├── data/             # CSV data files
├── windows/          # Windows timezone data
├── *.json           # Embedded data files
└── README.md        # This file

Usage Examples

Basic Usage
package main

import (
    "fmt"
    "time"
    "github.com/origadmin/toolkits/i18n/tz"
)

func main() {
    // Get current timezone
    loc, err := tz.GetLocation()
    if err != nil {
        panic(err)
    }
    
    fmt.Printf("Current timezone: %s\n", loc.String())
    
    // Convert time
    now := time.Now()
    converted, err := tz.ConvertTime(now, "UTC", "Asia/Shanghai")
    if err != nil {
        panic(err)
    }
    
    fmt.Printf("UTC: %s\n", now.UTC())
    fmt.Printf("Shanghai: %s\n", converted)
}
Advanced Usage
// Get detailed timezone information
info, err := tz.GetTimeZoneInfo("America/New_York")
if err != nil {
    panic(err)
}

fmt.Printf("Timezone: %s\n", info.Name)
fmt.Printf("Country: %s\n", info.Country)
fmt.Printf("Offset: %s\n", info.OffsetString)
fmt.Printf("DST: %t\n", info.IsDST)

// Find all timezones for a country
timezones, found := tz.FindTimeZonesByCountryCode("US")
if found {
    fmt.Printf("Found %d timezones for US\n", len(timezones))
    for _, tz := range timezones {
        fmt.Printf("- %s (%s)\n", tz.ZoneName, tz.Abbreviation)
    }
}

Documentation

Overview

Package tz implements the functions, types, and interfaces for the module.

Package tz implements the functions, types, and interfaces for the module.

Package tz implements the functions, types, and interfaces for the module.

Package tz implements the functions, types, and interfaces for the module.

Package tz implements the functions, types, and interfaces for the module.

Package tz implements the functions, types, and interfaces for the module.

Package tz implements the functions, types, and interfaces for the module.

Package tz implements enhanced Windows timezone support with caching and fallback strategies.

Package tz implements enhanced Windows timezone mapping with validation and fallback.

Index

Constants

View Source
const (
	OffsetCountryName = 0
	OffsetCountryCode = 1
)
View Source
const (
	OffsetZoneName         = 0
	OffsetZoneCountryCode  = 1
	OffsetZoneAbbreviation = 2
	OffsetZoneTimeStart    = 3
	OffsetZoneGmtOffset    = 4
	OffsetZoneDst          = 5
)

Variables

View Source
var (
	ErrTimeZoneNotFound        = errors.New("timezone not found")
	ErrInvalidTimeZone         = errors.New("invalid timezone format")
	ErrConversionFailed        = errors.New("timezone conversion failed")
	ErrLocationNotFound        = errors.New("location not found")
	ErrWindowsTimeZoneNotFound = errors.New("Windows timezone not found")
	ErrIANATimeZoneNotFound    = errors.New("IANA timezone not found")
	ErrNotImplemented          = errors.New("feature not implemented")
	ErrCacheExpired            = errors.New("cache expired")
	ErrDetectionFailed         = errors.New("timezone detection failed")
)

Common timezone errors

Functions

func ConvertTime

func ConvertTime(t time.Time, fromZone, toZone string) (time.Time, error)

ConvertTime converts time from one timezone to another

func ConvertWindowsToIANA

func ConvertWindowsToIANA(windowsID string) ([]string, bool)

ConvertWindowsToIANA converts a Windows timezone ID to IANA zones using the global mapper

func ConvertWindowsToPreferredIANA

func ConvertWindowsToPreferredIANA(windowsID string) (string, bool)

ConvertWindowsToPreferredIANA converts a Windows timezone ID to the preferred IANA zone

func GenerateJSON

func GenerateJSON() error

func GetLocation

func GetLocation() (*time.Location, error)

GetLocation returns the current system timezone

func GetLocationString

func GetLocationString() string

GetLocationString returns the current system timezone as string

func GetOffset

func GetOffset(zone string) (int64, error)

GetOffset returns timezone offset in seconds

func GetSystemTimezone

func GetSystemTimezone() (string, error)

GetSystemTimezone gets the current system timezone using enhanced detection

func IsDST

func IsDST(t time.Time, zone string) (bool, error)

IsDST checks if given time is DST in the specified timezone

Types

type Country

type Country struct {
	CountryName string `json:"country_name"`
	CountryCode string `json:"country_code"`
}

Country country_name,country_code

func CountriesFromCSV

func CountriesFromCSV(filePath string) ([]Country, error)

func GetCountries

func GetCountries() []Country

GetCountries returns all countries

type MappingError

type MappingError struct {
	Operation string
	Cause     error
}

MappingError represents errors during timezone mapping operations

func (*MappingError) Error

func (e *MappingError) Error() string

func (*MappingError) Unwrap

func (e *MappingError) Unwrap() error

type RawTimeZone

type RawTimeZone struct {
	ZoneName     string `json:"zone_name"`
	CountryCode  string `json:"country_code"`
	Abbreviation string `json:"abbreviation"`
	TimeStart    int64  `json:"time_start"`
	GmtOffset    int64  `json:"gmt_offset"`
	Dst          int64  `json:"dst"`
}

RawTimeZone represents the raw timezone data from JSON

type TimeZone

type TimeZone struct {
	ZoneName     string `json:"zone_name"`
	ZoneID       string `json:"zone_id"`
	CountryCode  string `json:"country_code"`
	Abbreviation string `json:"abbreviation"`
	TimeStart    int64  `json:"time_start"`
	GmtOffset    int64  `json:"gmt_offset"`
	Dst          int64  `json:"dst"` // 1 or 0 means DST
}

TimeZone zone_name,country_code,abbreviation,time_start,gmt_offset,dst

func FindTimeZoneByZoneName

func FindTimeZoneByZoneName(name string) (*TimeZone, bool)

FindTimeZoneByZoneName finds timezone by zone name

func FindTimeZonesByAbbreviation

func FindTimeZonesByAbbreviation(abbrev string) ([]*TimeZone, bool)

FindTimeZonesByAbbreviation finds timezones by abbreviation

func FindTimeZonesByCountryCode

func FindTimeZonesByCountryCode(code string) ([]*TimeZone, bool)

FindTimeZonesByCountryCode finds timezones by country code

func GetTimeZones

func GetTimeZones() []*TimeZone

GetTimeZones returns all timezones

func TimeZonesFromCSV

func TimeZonesFromCSV(filePath string) ([]TimeZone, error)

type TimeZoneConverter

type TimeZoneConverter interface {
	Convert(t time.Time, fromZone, toZone string) (time.Time, error)
	GetOffset(zone string) (int, error)
	IsDST(t time.Time, zone string) (bool, error)
}

TimeZoneConverter interface for timezone conversion

type TimeZoneFinder

type TimeZoneFinder interface {
	FindByZoneName(name string) (*TimeZone, bool)
	FindByCountryCode(code string) ([]*TimeZone, bool)
	FindByAbbreviation(abbrev string) ([]*TimeZone, bool)
	GetCurrentLocation() (*time.Location, error)
	GetAllTimeZones() []*TimeZone
}

TimeZoneFinder interface for finding timezones

type TimeZoneInfo

type TimeZoneInfo struct {
	Name         string         `json:"name"`
	Country      string         `json:"country"`
	Offset       int64          `json:"offset"`        // in seconds
	OffsetString string         `json:"offset_string"` // "+08:00" format
	IsDST        bool           `json:"is_dst"`
	Abbreviation string         `json:"abbreviation"`
	Location     *time.Location `json:"-"`
}

TimeZoneInfo provides detailed timezone information

func GetTimeZoneInfo

func GetTimeZoneInfo(name string) (*TimeZoneInfo, error)

GetTimeZoneInfo returns detailed timezone information

type TimezoneDetectionError

type TimezoneDetectionError struct {
	Method string
	Cause  error
}

TimezoneDetectionError represents errors during timezone detection

func (*TimezoneDetectionError) Error

func (e *TimezoneDetectionError) Error() string

func (*TimezoneDetectionError) Unwrap

func (e *TimezoneDetectionError) Unwrap() error

type WindowsMapper

type WindowsMapper struct {
	// contains filtered or unexported fields
}

WindowsMapper provides enhanced Windows timezone mapping capabilities

func NewWindowsMapper

func NewWindowsMapper() *WindowsMapper

NewWindowsMapper creates a new mapper instance

func (*WindowsMapper) GetAllMappings

func (m *WindowsMapper) GetAllMappings() map[string]WindowsTimeZoneMapping

GetAllMappings returns all timezone mappings

func (*WindowsMapper) IANAToWindows

func (m *WindowsMapper) IANAToWindows(ianaZone string) ([]string, bool)

IANAToWindows finds Windows timezone IDs that map to the given IANA zone

func (*WindowsMapper) LoadMappings

func (m *WindowsMapper) LoadMappings() error

LoadMappings loads timezone mappings from embedded data or external source

func (*WindowsMapper) ValidateMapping

func (m *WindowsMapper) ValidateMapping(windowsID, ianaZone string) error

ValidateMapping validates a Windows to IANA timezone mapping

func (*WindowsMapper) WindowsToIANA

func (m *WindowsMapper) WindowsToIANA(windowsID string) ([]string, bool)

WindowsToIANA converts a Windows timezone ID to IANA zones

func (*WindowsMapper) WindowsToPreferredIANA

func (m *WindowsMapper) WindowsToPreferredIANA(windowsID string) (string, bool)

WindowsToPreferredIANA converts a Windows timezone ID to the preferred IANA zone

type WindowsTimeZoneDetector

type WindowsTimeZoneDetector struct {
	// contains filtered or unexported fields
}

WindowsTimeZoneDetector provides enhanced Windows timezone detection

func NewWindowsTimeZoneDetector

func NewWindowsTimeZoneDetector(ttl time.Duration) *WindowsTimeZoneDetector

NewWindowsTimeZoneDetector creates a new detector with configurable TTL

func (*WindowsTimeZoneDetector) GetSystemTimezone

func (d *WindowsTimeZoneDetector) GetSystemTimezone() (string, error)

GetSystemTimezone safely gets the system timezone with caching

type WindowsTimeZoneMapping

type WindowsTimeZoneMapping struct {
	WindowsID   string    `json:"windows_id"`
	IANAZones   []string  `json:"iana_zones"`
	Territory   string    `json:"territory"`
	LastUpdated time.Time `json:"last_updated"`
	Preferred   string    `json:"preferred,omitempty"` // Preferred IANA zone for this Windows zone
}

WindowsTimeZoneMapping represents a mapping from Windows timezone to IANA zones

Jump to

Keyboard shortcuts

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