gtime_time_zone.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. package gtime
  7. import (
  8. "sync"
  9. "time"
  10. )
  11. var (
  12. // locationMap is time zone name to its location object.
  13. // Time zone name is like: Asia/Shanghai.
  14. locationMap = make(map[string]*time.Location)
  15. // locationMu is used for concurrent safety for `locationMap`.
  16. locationMu = sync.RWMutex{}
  17. )
  18. // ToLocation converts current time to specified location.
  19. func (t *Time) ToLocation(location *time.Location) *Time {
  20. newTime := t.Clone()
  21. newTime.Time = newTime.Time.In(location)
  22. return newTime
  23. }
  24. // ToZone converts current time to specified zone like: Asia/Shanghai.
  25. func (t *Time) ToZone(zone string) (*Time, error) {
  26. if location, err := t.getLocationByZoneName(zone); err == nil {
  27. return t.ToLocation(location), nil
  28. } else {
  29. return nil, err
  30. }
  31. }
  32. func (t *Time) getLocationByZoneName(name string) (location *time.Location, err error) {
  33. locationMu.RLock()
  34. location = locationMap[name]
  35. locationMu.RUnlock()
  36. if location == nil {
  37. location, err = time.LoadLocation(name)
  38. if err == nil && location != nil {
  39. locationMu.Lock()
  40. locationMap[name] = location
  41. locationMu.Unlock()
  42. }
  43. }
  44. return
  45. }
  46. // Local converts the time to local timezone.
  47. func (t *Time) Local() *Time {
  48. newTime := t.Clone()
  49. newTime.Time = newTime.Time.Local()
  50. return newTime
  51. }