File: timezone.go

package info (click to toggle)
miniflux 2.2.6-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 5,632 kB
  • sloc: xml: 4,843; javascript: 1,326; sh: 290; makefile: 179
file content (50 lines) | stat: -rw-r--r-- 1,249 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package timezone // import "miniflux.app/v2/internal/timezone"

import (
	"time"
)

// Convert converts provided date time to actual timezone.
func Convert(tz string, t time.Time) time.Time {
	userTimezone := getLocation(tz)

	if t.Location().String() == "" {
		if t.Before(time.Date(1, time.January, 1, 0, 0, 0, 0, time.UTC)) {
			return time.Date(0, time.January, 1, 0, 0, 0, 0, userTimezone)
		}

		// In this case, the provided date is already converted to the user timezone by Postgres,
		// but the timezone information is not set in the time struct.
		// We cannot use time.In() because the date will be converted a second time.
		return time.Date(
			t.Year(),
			t.Month(),
			t.Day(),
			t.Hour(),
			t.Minute(),
			t.Second(),
			t.Nanosecond(),
			userTimezone,
		)
	} else if t.Location() != userTimezone {
		return t.In(userTimezone)
	}

	return t
}

// Now returns the current time with the given timezone.
func Now(tz string) time.Time {
	return time.Now().In(getLocation(tz))
}

func getLocation(tz string) *time.Location {
	loc, err := time.LoadLocation(tz)
	if err != nil {
		loc = time.Local
	}
	return loc
}