Add initial project files
This commit is contained in:
37
pkg/people/birthday.go
Normal file
37
pkg/people/birthday.go
Normal file
@@ -0,0 +1,37 @@
|
||||
package people
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Declaring birthday layout constant
|
||||
const birthdayLayout = "2006-01-02" // YYYY-MM-DD - is default birthday layout
|
||||
|
||||
// Birthday is a custom encapsulation type for time.Time to handle birthdays
|
||||
// by decoding and encoding from and to JSON format
|
||||
type Birthday struct {
|
||||
time.Time // Embedding time.Time
|
||||
err error // Time parsing error
|
||||
}
|
||||
|
||||
// UnmarshalJSON decodes a date text to time.Time object
|
||||
func (t *Birthday) UnmarshalJSON(bytes []byte) (err error) {
|
||||
// 1. Decode the bytes into an int64
|
||||
// 2. Parse the unix timestamp
|
||||
|
||||
// Is value quoted?
|
||||
if rune(bytes[0]) == '"' || rune(bytes[0]) == '\'' {
|
||||
bytes = bytes[1 : len(bytes)-1] // remove quotes
|
||||
}
|
||||
|
||||
// Parse string to time.Time
|
||||
t.Time, t.err = time.Parse(birthdayLayout, string(bytes))
|
||||
t.err = err
|
||||
return
|
||||
}
|
||||
|
||||
// MarshalJSON encodes a time.Time object to date JSON text
|
||||
func (t Birthday) MarshalJSON() ([]byte, error) {
|
||||
return json.Marshal(t.Time.Format(birthdayLayout))
|
||||
}
|
||||
Reference in New Issue
Block a user