timezone.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // Copyright 2018 Frédéric Guillot. All rights reserved.
  2. // Use of this source code is governed by the Apache 2.0
  3. // license that can be found in the LICENSE file.
  4. package timezone // import "miniflux.app/timezone"
  5. import (
  6. "time"
  7. )
  8. // Convert converts provided date time to actual timezone.
  9. func Convert(tz string, t time.Time) time.Time {
  10. userTimezone := getLocation(tz)
  11. if t.Location().String() == "" {
  12. // In this case, the provided date is already converted to the user timezone by Postgres,
  13. // but the timezone information is not set in the time struct.
  14. // We cannot use time.In() because the date will be converted a second time.
  15. t = time.Date(
  16. t.Year(),
  17. t.Month(),
  18. t.Day(),
  19. t.Hour(),
  20. t.Minute(),
  21. t.Second(),
  22. t.Nanosecond(),
  23. userTimezone,
  24. )
  25. } else if t.Location() != userTimezone {
  26. t = t.In(userTimezone)
  27. }
  28. return t
  29. }
  30. // Now returns the current time with the given timezone.
  31. func Now(tz string) time.Time {
  32. return time.Now().In(getLocation(tz))
  33. }
  34. func getLocation(tz string) *time.Location {
  35. loc, err := time.LoadLocation(tz)
  36. if err != nil {
  37. loc = time.Local
  38. }
  39. return loc
  40. }