From 4844e946d3538a4c482d5b878e6c54dca2df97c9 Mon Sep 17 00:00:00 2001 From: Marco Cetica Date: Tue, 17 Jun 2025 10:11:10 +0200 Subject: [PATCH] Added custom date type --- model/weatherModel.go | 3 +-- types/date.go | 35 +++++++++++++++++++++++++++++++++++ types/weather.go | 12 +++++------- 3 files changed, 41 insertions(+), 9 deletions(-) create mode 100644 types/date.go diff --git a/model/weatherModel.go b/model/weatherModel.go index 0709991..4cb80ce 100644 --- a/model/weatherModel.go +++ b/model/weatherModel.go @@ -128,9 +128,8 @@ func GetWeather(city *types.City, apiKey string) (types.Weather, error) { } // Format UNIX timestamp as 'YYYY-MM-DD' - // unixTs, _ := strconv.Atoi(weather.Current.Timestamp) utcTime := time.Unix(int64(weather.Current.Timestamp), 0) - weatherDate := utcTime.UTC() + weatherDate := &types.ZephyrDate{Time: utcTime.UTC()} // Set condition accordingly to weather description var condition string diff --git a/types/date.go b/types/date.go new file mode 100644 index 0000000..a2e27bb --- /dev/null +++ b/types/date.go @@ -0,0 +1,35 @@ +package types + +import ( + "strings" + "time" +) + +type ZephyrDate struct { + time.Time +} + +func (date *ZephyrDate) UnmarshalJSON(b []byte) error { + s := strings.Trim(string(b), "\"") + if s == "" { + return nil + } + + var err error + date.Time, err = time.Parse("Monday, 2006/01/02", s) + if err != nil { + return err + } + + return nil +} + +func (date *ZephyrDate) MarshalJSON() ([]byte, error) { + if date.Time.IsZero() { + return []byte("\"\""), nil + } + + fmtDate := date.Time.Format("Monday, 2006/01/02") + + return []byte("\"" + fmtDate + "\""), nil +} diff --git a/types/weather.go b/types/weather.go index cb3ca66..2391544 100644 --- a/types/weather.go +++ b/types/weather.go @@ -1,12 +1,10 @@ package types -import "time" - // The Weather data type, representing the weather of a certain city type Weather struct { - Date time.Time `json:"date"` - Temperature string `json:"temperature"` - Condition string `json:"condition"` - FeelsLike string `json:"feelsLike"` - Emoji string `json:"emoji"` + Date *ZephyrDate `json:"date"` + Temperature string `json:"temperature"` + Condition string `json:"condition"` + FeelsLike string `json:"feelsLike"` + Emoji string `json:"emoji"` }