Skip to content

Instantly share code, notes, and snippets.

@ernado
Last active December 1, 2017 16:30
Show Gist options
  • Save ernado/1f5cd0af5d80e19a2d1a9a3132ae83aa to your computer and use it in GitHub Desktop.
Save ernado/1f5cd0af5d80e19a2d1a9a3132ae83aa to your computer and use it in GitHub Desktop.
Card Expiration Parsing PD-2814
// Expiration wraps month and year of card expiration.
type Expiration struct {
Month time.Month
Year int
}
// LocalDate returns LocalDate that is equal to expiration date.
func (e Expiration) LocalDate() LocalDate {
return Date(e.Year, e.Month, 1)
}
func (e Expiration) String() string {
return fmt.Sprintf("%02d/%d", e.Month, e.Year)
}
// StringShort returns short format of expiration date, e.g. 0422 for April
// 2022.
func (e Expiration) StringShort() string {
return fmt.Sprintf("%02d%02d", e.Month, e.Year%expirationDefaultYear)
}
// ParseShort parses s as short format of expiration date returning error
// if any.
func (e *Expiration) ParseShort(s string) error {
if len(s) != 4 {
return errors.Errorf("unexpected length of expiration date %q", len(s))
}
m, err := strconv.Atoi(s[:2])
if err != nil {
return errors.Wrap(err, "bad month value")
}
y, err := strconv.Atoi(s[2:])
if err != nil {
return errors.Wrap(err, "bad year value")
}
e.Month = time.Month(m)
e.Year = y + expirationDefaultYear
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment