@@ -130,6 +130,74 @@ abstract class TimeRange {
130
130
@override
131
131
int get hashCode => Object .hash (from, to, isUtc);
132
132
133
+ /// You can reconstruct [this] by passing the return value to
134
+ /// [TimeRange.parse] .
135
+ ///
136
+ /// Serializes [DateTime] to ISO 8601 string, therefore preserves
137
+ /// [from] and [to] 's timezone information.
133
138
@override
134
- String toString () => "TimeRange($from -> $to )" ;
139
+ String toString () {
140
+ if (this is HourTimeRange ) {
141
+ return "HourTimeRange:${from .toIso8601String ()}" ;
142
+ }
143
+ if (this is DayTimeRange ) {
144
+ return "DayTimeRange:${from .toIso8601String ()}" ;
145
+ }
146
+ if (this is LocalWeekTimeRange ) {
147
+ return "LocalWeekTimeRange:${from .toIso8601String ()}" ;
148
+ }
149
+ if (this is MonthTimeRange ) {
150
+ return "MonthTimeRange:${from .toIso8601String ()}" ;
151
+ }
152
+ if (this is YearTimeRange ) {
153
+ return "YearTimeRange:${from .toIso8601String ()}" ;
154
+ }
155
+
156
+ return "CustomTimeRange:${from .toIso8601String ()}:${to .toIso8601String ()}" ;
157
+ }
158
+
159
+ /// Parses string generated by [toString]
160
+ ///
161
+ /// Throws [FormatException] if the string is not in the correct format
162
+ static TimeRange parse (String serialized) {
163
+ final TimeRange ? result = tryParse (serialized);
164
+
165
+ if (result == null ) {
166
+ throw const FormatException (
167
+ "Cannot parse TimeRange from serialized string" ,
168
+ );
169
+ }
170
+
171
+ return result;
172
+ }
173
+
174
+ /// Parses string generated by [toString]
175
+ ///
176
+ /// Returns null in any case of failure
177
+ static TimeRange ? tryParse (String serialized) {
178
+ final List <String > parts = serialized.split (":" );
179
+
180
+ if (parts.length < 2 ) return null ;
181
+
182
+ final DateTime ? from = DateTime .tryParse (parts[1 ]);
183
+ final DateTime ? to = parts.length > 2 ? DateTime .tryParse (parts[2 ]) : null ;
184
+
185
+ if (from == null ) return null ;
186
+ if (parts.first == "CustomTimeRange" && to == null ) return null ;
187
+
188
+ switch (parts[0 ]) {
189
+ case "HourTimeRange" :
190
+ return HourTimeRange .fromDateTime (from);
191
+ case "DayTimeRange" :
192
+ return DayTimeRange .fromDateTime (from);
193
+ case "LocalWeekTimeRange" :
194
+ return LocalWeekTimeRange (from);
195
+ case "MonthTimeRange" :
196
+ return MonthTimeRange .fromDateTime (from);
197
+ case "YearTimeRange" :
198
+ return YearTimeRange .fromDateTime (from);
199
+ default :
200
+ return CustomTimeRange (from, to! );
201
+ }
202
+ }
135
203
}
0 commit comments