timezone.go 1.1 KB

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