Skip to content

Commit cfa04c8

Browse files
author
leonlux
committed
change example to keep using DateTime<Utc> and update playground hash.
1 parent a0aa632 commit cfa04c8

File tree

1 file changed

+13
-17
lines changed

1 file changed

+13
-17
lines changed

_src/custom-date-format.md

Lines changed: 13 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -4,27 +4,27 @@ This uses the [`chrono`](https://github.com/chronotope/chrono) crate to
44
serialize and deserialize JSON data containing a custom date format. The `with`
55
attribute is used to provide the logic for handling the custom representation.
66

7-
!PLAYGROUND 7185eb211a4822ce97184ae25fedda91
7+
!PLAYGROUND 8989865329b35bed5828ff7f7f4747f4
88
```rust
9-
use chrono::NaiveDateTime;
10-
use serde::{Serialize, Deserialize};
9+
use chrono::{DateTime, Utc};
10+
use serde::{Deserialize, Serialize};
1111

1212
#[derive(Serialize, Deserialize, Debug)]
1313
pub struct StructWithCustomDate {
1414
// DateTime supports Serde out of the box, but uses RFC3339 format. Provide
1515
// some custom logic to make it use our desired format.
1616
#[serde(with = "my_date_format")]
17-
pub timestamp: NaiveDateTime,
17+
pub timestamp: DateTime<Utc>,
1818

1919
// Any other fields in the struct.
2020
pub bidder: String,
2121
}
2222

2323
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};
2626

27-
const FORMAT: &'static str = "%Y-%m-%d %H:%M:%S";
27+
const FORMAT: &'static str = "%Y-%m-%d %H:%M:%S %z";
2828

2929
// The signature of a serialize_with function must follow the pattern:
3030
//
@@ -33,10 +33,7 @@ mod my_date_format {
3333
// S: Serializer
3434
//
3535
// 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>
4037
where
4138
S: Serializer,
4239
{
@@ -51,22 +48,21 @@ mod my_date_format {
5148
// D: Deserializer<'de>
5249
//
5350
// 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>
5752
where
5853
D: Deserializer<'de>,
5954
{
6055
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))
6259
}
63-
6460
}
6561

6662
fn main() {
6763
let json_str = r#"
6864
{
69-
"timestamp": "2017-02-16 21:54:30",
65+
"timestamp": "2017-02-16 21:54:30 +00:00",
7066
"bidder": "Skrillex"
7167
}
7268
"#;

0 commit comments

Comments
 (0)