github.com/pingcap/ticdc@v0.0.0-20220526033649-485a10ef2652/pkg/util/tz.go (about) 1 // Copyright 2020 PingCAP, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package util 15 16 import ( 17 "os" 18 "path/filepath" 19 "strings" 20 "time" 21 22 cerror "github.com/pingcap/ticdc/pkg/errors" 23 ) 24 25 // GetTimezone returns the timezone specified by the name 26 func GetTimezone(name string) (tz *time.Location, err error) { 27 switch strings.ToLower(name) { 28 case "", "system", "local": 29 tz, err = GetLocalTimezone() 30 err = cerror.WrapError(cerror.ErrLoadTimezone, err) 31 default: 32 tz, err = time.LoadLocation(name) 33 err = cerror.WrapError(cerror.ErrLoadTimezone, err) 34 } 35 return 36 } 37 38 func getTimezoneFromZonefile(zonefile string) (tz *time.Location, err error) { 39 // the linked path of `/etc/localtime` sample: 40 // MacOS: /var/db/timezone/zoneinfo/Asia/Shanghai 41 // Linux: /usr/share/zoneinfo/Asia/Shanghai 42 region := filepath.Base(filepath.Dir(zonefile)) 43 zone := filepath.Base(zonefile) 44 var tzName string 45 if region == "zoneinfo" { 46 tzName = zone 47 } else { 48 tzName = filepath.Join(region, zone) 49 } 50 tz, err = time.LoadLocation(tzName) 51 err = cerror.WrapError(cerror.ErrLoadTimezone, err) 52 return 53 } 54 55 // GetLocalTimezone returns the timezone in local system 56 func GetLocalTimezone() (*time.Location, error) { 57 if time.Local.String() != "Local" { 58 return time.Local, nil 59 } 60 str, err := os.Readlink("/etc/localtime") 61 if err != nil { 62 return nil, cerror.WrapError(cerror.ErrLoadTimezone, err) 63 } 64 return getTimezoneFromZonefile(str) 65 }