GetTimezone tries to find local timezone from the path, that can be either $TZ environment variable or /etc/localtime symlink
(path string)
| 450 | // GetTimezone tries to find local timezone from the path, that can be |
| 451 | // either $TZ environment variable or /etc/localtime symlink |
| 452 | func GetTimezone(path string) (string, error) { |
| 453 | // Use case-insensitive search for /zoneinfo/ in the file path. |
| 454 | regex := regexp.MustCompile(`(?i)/.*?zoneinfo.*?/`) |
| 455 | parts := regex.Split(strings.TrimSpace(path), 2) |
| 456 | if len(parts) != 2 { |
| 457 | // If this is not a path, but timezone, return it. |
| 458 | _, err := time.LoadLocation(path) |
| 459 | if err == nil { |
| 460 | return path, nil |
| 461 | } |
| 462 | return "", fmt.Errorf("unable to read timezone from %s", path) |
| 463 | } |
| 464 | timezone := parts[1] |
| 465 | // Remove leading prefixes if they exist. |
| 466 | // https://stackoverflow.com/a/67888343/8097891 |
| 467 | for _, prefix := range []string{"posix/", "right/"} { |
| 468 | timezone = strings.TrimPrefix(timezone, prefix) |
| 469 | } |
| 470 | if timezone == "" { |
| 471 | return "", fmt.Errorf("unable to read timezone from %s", path) |
| 472 | } |
| 473 | _, err := time.LoadLocation(timezone) |
| 474 | if err != nil { |
| 475 | return "", fmt.Errorf("failed to load timezone '%s': %v", timezone, err) |
| 476 | } |
| 477 | return timezone, nil |
| 478 | } |
| 479 | |
| 480 | // GetLocalTimezone tries to find local timezone from $TZ or /etc/localtime symlink |
| 481 | func GetLocalTimezone() (string, error) { |