-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathdate_time_converter.dart
44 lines (38 loc) · 1.15 KB
/
date_time_converter.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import 'package:freezed_annotation/freezed_annotation.dart';
/// {@template date_time_converter_nullable}
/// {@macro date_time_converter}
///
/// If the json is null, this will return null
/// {@endtemplate}
class DateTimeConverterNullable extends JsonConverter<DateTime?, dynamic> {
/// {@macro date_time_converter_nullable}
const DateTimeConverterNullable();
@override
DateTime? fromJson(dynamic json) {
if (json == null) return null;
return const DateTimeConverter().fromJson(json);
}
@override
String? toJson(DateTime? object) {
if (object == null) return null;
return const DateTimeConverter().toJson(object);
}
}
/// {@template date_time_converter}
/// This is a custom json converter for [DateTime]
///
/// This will parse the date time from a ISO8601 string
/// {@endtemplate}
class DateTimeConverter extends JsonConverter<DateTime, dynamic> {
/// {@macro date_time_converter}
const DateTimeConverter();
@override
DateTime fromJson(dynamic json) {
if (json is DateTime) return json;
return DateTime.parse(json as String);
}
@override
String toJson(DateTime object) {
return object.toIso8601String();
}
}