Skip to content

Commit 0dfe85a

Browse files
author
leonlux
committed
update example to keep using the original format string
1 parent cfa04c8 commit 0dfe85a

File tree

1 file changed

+19
-15
lines changed

1 file changed

+19
-15
lines changed

_src/custom-date-format.md

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,10 @@ 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 8989865329b35bed5828ff7f7f4747f4
7+
!PLAYGROUND 2ef7c347c76b030fe7e8c59ce9efccd3
88
```rust
99
use chrono::{DateTime, Utc};
10-
use serde::{Deserialize, Serialize};
10+
use serde::{Serialize, Deserialize};
1111

1212
#[derive(Serialize, Deserialize, Debug)]
1313
pub struct StructWithCustomDate {
@@ -21,10 +21,10 @@ pub struct StructWithCustomDate {
2121
}
2222

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

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

2929
// The signature of a serialize_with function must follow the pattern:
3030
//
@@ -33,9 +33,12 @@ 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>(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,
3942
{
4043
let s = format!("{}", date.format(FORMAT));
4144
serializer.serialize_str(&s)
@@ -48,21 +51,22 @@ mod my_date_format {
4851
// D: Deserializer<'de>
4952
//
5053
// 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>,
5459
{
5560
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))
5963
}
6064
}
6165

6266
fn main() {
6367
let json_str = r#"
6468
{
65-
"timestamp": "2017-02-16 21:54:30 +00:00",
69+
"timestamp": "2017-02-16 21:54:30",
6670
"bidder": "Skrillex"
6771
}
6872
"#;

0 commit comments

Comments
 (0)