@@ -4,10 +4,10 @@ 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 8989865329b35bed5828ff7f7f4747f4
7
+ !PLAYGROUND 2ef7c347c76b030fe7e8c59ce9efccd3
8
8
``` rust
9
9
use chrono :: {DateTime , Utc };
10
- use serde :: {Deserialize , Serialize };
10
+ use serde :: {Serialize , Deserialize };
11
11
12
12
#[derive(Serialize , Deserialize , Debug )]
13
13
pub struct StructWithCustomDate {
@@ -21,10 +21,10 @@ pub struct StructWithCustomDate {
21
21
}
22
22
23
23
mod my_date_format {
24
- use chrono :: {DateTime , Utc };
25
- use serde :: {self , Deserialize , Deserializer , Serializer };
24
+ use chrono :: {DateTime , Utc , NaiveDateTime };
25
+ use serde :: {self , Deserialize , Serializer , Deserializer };
26
26
27
- const FORMAT : & 'static str = " %Y-%m-%d %H:%M:%S %z " ;
27
+ const FORMAT : & 'static str = " %Y-%m-%d %H:%M:%S" ;
28
28
29
29
// The signature of a serialize_with function must follow the pattern:
30
30
//
@@ -33,9 +33,12 @@ 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 >(date : & DateTime <Utc >, serializer : S ) -> Result <S :: Ok , S :: Error >
37
- where
38
- S : Serializer ,
36
+ pub fn serialize <S >(
37
+ date : & DateTime <Utc >,
38
+ serializer : S ,
39
+ ) -> Result <S :: Ok , S :: Error >
40
+ where
41
+ S : Serializer ,
39
42
{
40
43
let s = format! (" {}" , date . format (FORMAT ));
41
44
serializer . serialize_str (& s )
@@ -48,21 +51,22 @@ mod my_date_format {
48
51
// D: Deserializer<'de>
49
52
//
50
53
// although it may also be generic over the output types T.
51
- pub fn deserialize <'de , D >(deserializer : D ) -> Result <DateTime <Utc >, D :: Error >
52
- where
53
- D : Deserializer <'de >,
54
+ pub fn deserialize <'de , D >(
55
+ deserializer : D ,
56
+ ) -> Result <DateTime <Utc >, D :: Error >
57
+ where
58
+ D : Deserializer <'de >,
54
59
{
55
60
let s = String :: deserialize (deserializer )? ;
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 ))
61
+ let dt = NaiveDateTime :: parse_from_str (& s , FORMAT ). map_err (serde :: de :: Error :: custom )? ;
62
+ Ok (DateTime :: <Utc >:: from_naive_utc_and_offset (dt , Utc ))
59
63
}
60
64
}
61
65
62
66
fn main () {
63
67
let json_str = r # "
64
68
{
65
- "timestamp": "2017-02-16 21:54:30 +00:00 ",
69
+ "timestamp": "2017-02-16 21:54:30",
66
70
"bidder": "Skrillex"
67
71
}
68
72
" # ;
0 commit comments