parser.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package date // import "miniflux.app/v2/internal/reader/date"
  4. import (
  5. "errors"
  6. "fmt"
  7. "strconv"
  8. "strings"
  9. "time"
  10. )
  11. // Parse parses a date found in a feed: a Unix timestamp, or a date in one of the
  12. // many formats listed in layouts, possibly with localized names.
  13. func Parse(rawInput string) (time.Time, error) {
  14. input := strings.TrimSpace(rawInput)
  15. if input == "" {
  16. return time.Time{}, errors.New(`date parser: empty value`)
  17. }
  18. if timestamp, err := strconv.ParseInt(input, 10, 64); err == nil {
  19. return time.Unix(timestamp, 0), nil
  20. }
  21. value, wallClockLocation := replaceIANATimezone(input)
  22. value = padShortOffset(normalizeRFC3339Separators(replacer.Replace(value)))
  23. parsed, ok := parseLayouts(value)
  24. if !ok {
  25. return time.Time{}, fmt.Errorf(`date parser: failed to parse date "%s"`, input)
  26. }
  27. if wallClockLocation != nil {
  28. parsed = withWallClockIn(parsed, wallClockLocation)
  29. }
  30. return checkTimezoneRange(parsed), nil
  31. }
  32. // parseLayouts parses the value with the first layout that matches it.
  33. func parseLayouts(value string) (time.Time, bool) {
  34. location := timezoneLocation(value)
  35. for _, layout := range layouts {
  36. if parsed, err := time.ParseInLocation(layout, value, location); err == nil {
  37. return parsed, true
  38. }
  39. }
  40. return time.Time{}, false
  41. }
  42. // normalizeRFC3339Separators upper-cases the "t" separator and the "z" time zone
  43. // designator of RFC 3339 date-times. RFC 3339 section 5.6 allows them to be
  44. // lower case, but time.Parse only accepts upper case.
  45. func normalizeRFC3339Separators(value string) string {
  46. if len(value) < 11 || value[4] != '-' || value[7] != '-' || (value[10] != 't' && value[10] != 'T') {
  47. return value
  48. }
  49. value = value[:10] + "T" + value[11:]
  50. if strings.HasSuffix(value, "z") {
  51. value = value[:len(value)-1] + "Z"
  52. }
  53. return value
  54. }