Skip to content

Commit 01bec5c

Browse files
authoredFeb 28, 2025··
fix: add timestamp parsing to MAASTime (#113)
1 parent 4824e40 commit 01bec5c

File tree

2 files changed

+29
-11
lines changed

2 files changed

+29
-11
lines changed
 

‎entity/machine.go

+14-5
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package entity
33
import (
44
"encoding/json"
55
"errors"
6+
"fmt"
67
"net"
78
"strconv"
89
"time"
@@ -134,14 +135,22 @@ func (t *MAASTime) UnmarshalJSON(data []byte) error {
134135
return err
135136
}
136137

137-
temp, err := time.Parse("2006-01-02T15:04:05.999", str)
138-
if err != nil {
139-
return err
138+
formats := []string{
139+
"2006-01-02T15:04:05.999+00:00",
140+
"2006-01-02T15:04:05.999Z",
141+
"2006-01-02T15:04:05.999",
140142
}
141143

142-
*t = MAASTime(temp)
144+
for _, format := range formats {
145+
foundTime, err := time.Parse(format, str)
146+
if err == nil {
147+
*t = MAASTime(foundTime)
143148

144-
return nil
149+
return nil
150+
}
151+
}
152+
153+
return fmt.Errorf("unsupported time format for %q", str)
145154
}
146155

147156
// String returns MAASTime in RFC3339Nano format

‎entity/machine_test.go

+15-6
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package entity
22

33
import (
44
"encoding/json"
5+
"fmt"
56
"testing"
67

78
"github.com/canonical/gomaasclient/test/helper"
@@ -93,14 +94,22 @@ func TestMAASTimeUnmarshalJSON(t *testing.T) {
9394
Time MAASTime
9495
}{}
9596

96-
data := []byte(`{"Time": "2023-05-11T21:15:04.208"}`)
97-
if err := json.Unmarshal(data, &temp); err != nil {
98-
t.Fatal(err)
97+
formats := []string{
98+
"2023-05-11T21:15:04.208+00:00",
99+
"2023-05-11T21:15:04.208Z",
100+
"2023-05-11T21:15:04.208",
99101
}
100102

101-
expected := "2023-05-11T21:15:04.208Z"
102-
if temp.Time.String() != expected {
103-
t.Fatalf("expected %v, got %v", expected, temp.Time.String())
103+
for _, format := range formats {
104+
data := []byte(fmt.Sprintf(`{"Time": "%s"}`, format))
105+
if err := json.Unmarshal(data, &temp); err != nil {
106+
t.Fatal(err)
107+
}
108+
109+
expected := "2023-05-11T21:15:04.208Z"
110+
if temp.Time.String() != expected {
111+
t.Fatalf("expected %v, got %v", expected, temp.Time.String())
112+
}
104113
}
105114
}
106115

0 commit comments

Comments
 (0)
Please sign in to comment.