Skip to content

Commit

Permalink
Merge pull request #21 from zostay/fix-dates
Browse files Browse the repository at this point in the history
handle Mon Jan 02 15:04:05 2006 MST
  • Loading branch information
zostay committed Jan 31, 2023
2 parents a7fcfa7 + 329f595 commit fdc33e7
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 6 deletions.
4 changes: 4 additions & 0 deletions Changes.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
WIP TBD

* Bugfix: Handle another strange date I have come across in my sample data.

v2.3.0 2023-01-30

* On `header.ErrManyFields` failure, `(*header.Header).Get()` now returns the value of the first field found with the error.
Expand Down
28 changes: 22 additions & 6 deletions message/header/header.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package header

import (
"errors"
"fmt"
"net/mail"
"strings"
"time"
Expand Down Expand Up @@ -54,6 +55,13 @@ const (
To = "To"
)

// Even more custom date formats, built from those seen in the wild that the
// usual parsers have trouble with.
const (
// UnixDateWithEarlyYear is a weird one, eh?
UnixDateWithEarlyYear = "Mon Jan 02 15:04:05 2006 MST"
)

// Header wraps a Base, which does the actual storage and low-level field
// manipulation. This provides several methods to make reading and manipulating
// the header more convenient and some caching for complex values parsed from
Expand Down Expand Up @@ -139,13 +147,21 @@ func (h *Header) Get(name string) (string, error) {
// It either returns a parsed time or the parse error.
func ParseTime(body string) (time.Time, error) {
t, err := mail.ParseDate(body)
if err != nil {
t, err = dateparse.ParseAny(body)
if err != nil {
return t, err
}
if err == nil {
return t, nil
}
return t, nil

t, err = dateparse.ParseAny(body)
if err == nil {
return t, nil
}

t, err = time.Parse(UnixDateWithEarlyYear, body)
if err == nil {
return t, nil
}

return t, fmt.Errorf("time string %q cannot be parsed", body)
}

// getTime parses the header body as a date and caches the result.
Expand Down

0 comments on commit fdc33e7

Please sign in to comment.