github.com/gogf/gf@v1.16.9/os/gtime/gtime_time_zone.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/gogf/gf. 6 7 package gtime 8 9 import ( 10 "sync" 11 "time" 12 ) 13 14 var ( 15 // locationMap is time zone name to its location object. 16 // Time zone name is like: Asia/Shanghai. 17 locationMap = make(map[string]*time.Location) 18 19 // locationMu is used for concurrent safety for `locationMap`. 20 locationMu = sync.RWMutex{} 21 ) 22 23 // ToLocation converts current time to specified location. 24 func (t *Time) ToLocation(location *time.Location) *Time { 25 newTime := t.Clone() 26 newTime.Time = newTime.Time.In(location) 27 return newTime 28 } 29 30 // ToZone converts current time to specified zone like: Asia/Shanghai. 31 func (t *Time) ToZone(zone string) (*Time, error) { 32 if location, err := t.getLocationByZoneName(zone); err == nil { 33 return t.ToLocation(location), nil 34 } else { 35 return nil, err 36 } 37 } 38 39 func (t *Time) getLocationByZoneName(name string) (location *time.Location, err error) { 40 locationMu.RLock() 41 location = locationMap[name] 42 locationMu.RUnlock() 43 if location == nil { 44 location, err = time.LoadLocation(name) 45 if err == nil && location != nil { 46 locationMu.Lock() 47 locationMap[name] = location 48 locationMu.Unlock() 49 } 50 } 51 return 52 } 53 54 // Local converts the time to local timezone. 55 func (t *Time) Local() *Time { 56 newTime := t.Clone() 57 newTime.Time = newTime.Time.Local() 58 return newTime 59 }