@@ -4,27 +4,27 @@ This uses the [`chrono`](https://github.com/chronotope/chrono) crate to
4
4
serialize and deserialize JSON data containing a custom date format. The ` with `
5
5
attribute is used to provide the logic for handling the custom representation.
6
6
7
- !PLAYGROUND 7185eb211a4822ce97184ae25fedda91
7
+ !PLAYGROUND 8989865329b35bed5828ff7f7f4747f4
8
8
``` rust
9
- use chrono :: NaiveDateTime ;
10
- use serde :: {Serialize , Deserialize };
9
+ use chrono :: { DateTime , Utc } ;
10
+ use serde :: {Deserialize , Serialize };
11
11
12
12
#[derive(Serialize , Deserialize , Debug )]
13
13
pub struct StructWithCustomDate {
14
14
// DateTime supports Serde out of the box, but uses RFC3339 format. Provide
15
15
// some custom logic to make it use our desired format.
16
16
#[serde(with = " my_date_format" )]
17
- pub timestamp : NaiveDateTime ,
17
+ pub timestamp : DateTime < Utc > ,
18
18
19
19
// Any other fields in the struct.
20
20
pub bidder : String ,
21
21
}
22
22
23
23
mod my_date_format {
24
- use chrono :: NaiveDateTime ;
25
- use serde :: {self , Deserialize , Serializer , Deserializer };
24
+ use chrono :: { DateTime , Utc } ;
25
+ use serde :: {self , Deserialize , Deserializer , Serializer };
26
26
27
- const FORMAT : & 'static str = " %Y-%m-%d %H:%M:%S" ;
27
+ const FORMAT : & 'static str = " %Y-%m-%d %H:%M:%S %z " ;
28
28
29
29
// The signature of a serialize_with function must follow the pattern:
30
30
//
@@ -33,10 +33,7 @@ mod my_date_format {
33
33
// S: Serializer
34
34
//
35
35
// although it may also be generic over the input types T.
36
- pub fn serialize <S >(
37
- date : & NaiveDateTime ,
38
- serializer : S ,
39
- ) -> Result <S :: Ok , S :: Error >
36
+ pub fn serialize <S >(date : & DateTime <Utc >, serializer : S ) -> Result <S :: Ok , S :: Error >
40
37
where
41
38
S : Serializer ,
42
39
{
@@ -51,22 +48,21 @@ mod my_date_format {
51
48
// D: Deserializer<'de>
52
49
//
53
50
// although it may also be generic over the output types T.
54
- pub fn deserialize <'de , D >(
55
- deserializer : D ,
56
- ) -> Result <NaiveDateTime , D :: Error >
51
+ pub fn deserialize <'de , D >(deserializer : D ) -> Result <DateTime <Utc >, D :: Error >
57
52
where
58
53
D : Deserializer <'de >,
59
54
{
60
55
let s = String :: deserialize (deserializer )? ;
61
- NaiveDateTime :: parse_from_str (& s , FORMAT ). map_err (serde :: de :: Error :: custom )
56
+ let date_fixed_offset =
57
+ DateTime :: parse_from_str (& s , FORMAT ). map_err (serde :: de :: Error :: custom )? ;
58
+ Ok (date_fixed_offset . with_timezone (& Utc ))
62
59
}
63
-
64
60
}
65
61
66
62
fn main () {
67
63
let json_str = r # "
68
64
{
69
- "timestamp": "2017-02-16 21:54:30",
65
+ "timestamp": "2017-02-16 21:54:30 +00:00 ",
70
66
"bidder": "Skrillex"
71
67
}
72
68
" # ;
0 commit comments