Skip to content

Commit 897a50f

Browse files
yuankunzhangcakebaker
authored andcommitted
fix base datetime handling in the builder
1 parent 96f4771 commit 897a50f

File tree

2 files changed

+29
-19
lines changed

2 files changed

+29
-19
lines changed

src/items/builder.rs

Lines changed: 23 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -105,16 +105,28 @@ impl DateTimeBuilder {
105105

106106
pub(super) fn build(self) -> Option<DateTime<FixedOffset>> {
107107
let base = self.base.unwrap_or_else(|| chrono::Local::now().into());
108-
let mut dt = new_date(
109-
base.year(),
110-
base.month(),
111-
base.day(),
112-
0,
113-
0,
114-
0,
115-
0,
116-
*base.offset(),
117-
)?;
108+
109+
// If any of the following items are set, we truncate the time portion
110+
// of the base date to zero; otherwise, we use the base date as is.
111+
let mut dt = if self.timestamp.is_none()
112+
&& self.date.is_none()
113+
&& self.time.is_none()
114+
&& self.weekday.is_none()
115+
&& self.timezone.is_none()
116+
{
117+
base
118+
} else {
119+
new_date(
120+
base.year(),
121+
base.month(),
122+
base.day(),
123+
0,
124+
0,
125+
0,
126+
0,
127+
*base.offset(),
128+
)?
129+
};
118130

119131
if let Some(ts) = self.timestamp {
120132
// TODO: How to make the fract -> nanosecond conversion more precise?
@@ -221,14 +233,6 @@ impl DateTimeBuilder {
221233
}
222234

223235
for rel in self.relative {
224-
if self.timestamp.is_none()
225-
&& self.date.is_none()
226-
&& self.time.is_none()
227-
&& self.weekday.is_none()
228-
{
229-
dt = base;
230-
}
231-
232236
match rel {
233237
relative::Relative::Years(x) => {
234238
dt = dt.with_year(dt.year() + x)?;
@@ -254,7 +258,7 @@ impl DateTimeBuilder {
254258
relative::Relative::Minutes(x) => {
255259
dt += chrono::Duration::try_minutes(x.into())?;
256260
}
257-
// Seconds are special because they can be given as a float
261+
// Seconds are special because they can be given as a float.
258262
relative::Relative::Seconds(x) => {
259263
dt += chrono::Duration::try_seconds(x as i64)?;
260264
}

src/items/mod.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -446,6 +446,12 @@ mod tests {
446446
assert_eq!(result.minute(), now.minute());
447447
assert_eq!(result.second(), now.second());
448448

449+
let result = at_date(parse(&mut "2 days 3 days ago").unwrap(), now).unwrap();
450+
assert_eq!(result, now - chrono::Duration::days(1));
451+
assert_eq!(result.hour(), now.hour());
452+
assert_eq!(result.minute(), now.minute());
453+
assert_eq!(result.second(), now.second());
454+
449455
let result = at_date(parse(&mut "2025-01-01 2 days ago").unwrap(), now).unwrap();
450456
assert_eq!(result.hour(), 0);
451457
assert_eq!(result.minute(), 0);

0 commit comments

Comments
 (0)