timezone.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. if t.Before(time.Date(1, time.January, 1, 0, 0, 0, 0, time.UTC)) {
  12. return time.Date(0, time.January, 1, 0, 0, 0, 0, userTimezone)
  13. }
  14. // In this case, the provided date is already converted to the user timezone by Postgres,
  15. // but the timezone information is not set in the time struct.
  16. // We cannot use time.In() because the date will be converted a second time.
  17. return time.Date(
  18. t.Year(),
  19. t.Month(),
  20. t.Day(),
  21. t.Hour(),
  22. t.Minute(),
  23. t.Second(),
  24. t.Nanosecond(),
  25. userTimezone,
  26. )
  27. } else if t.Location() != userTimezone {
  28. return t.In(userTimezone)
  29. }
  30. return t
  31. }
  32. // Now returns the current time with the given timezone.
  33. func Now(tz string) time.Time {
  34. return time.Now().In(getLocation(tz))
  35. }
  36. func getLocation(tz string) *time.Location {
  37. loc, err := time.LoadLocation(tz)
  38. if err != nil {
  39. loc = time.Local
  40. }
  41. return loc
  42. }