use crate::{Context, Error, Outcome, Plugin, number, re};
use chrono::{Datelike, Days, Duration, Months, NaiveDate, Offset, TimeZone, Timelike, Weekday};
use num_traits::ToPrimitive;
pub struct Calendar;
pub(crate) fn date(s: &str, ctx: &Context) -> Option<NaiveDate> {
date_expression(s, ctx, 0, false)
}
fn date_expression(s: &str, ctx: &Context, depth: usize, extended: bool) -> Option<NaiveDate> {
if depth > 64 {
return None;
}
let s = super::syntax::ungroup(s);
if !extended && re!(r"^\d{4}-\d{2}-\d{2}-\d").is_match(s) {
return None;
}
let normalized = s.trim().to_lowercase();
let s = normalized.as_str();
let today = ctx.now.with_timezone(&ctx.timezone).date_naive();
match s.to_lowercase().as_str() {
"today" | "now" => return Some(today),
"tomorrow" => return today.checked_add_days(Days::new(1)),
"yesterday" => return today.checked_sub_days(Days::new(1)),
_ => {}
}
if let Some((q, unit)) = s.split_once(' ')
&& matches!(q, "next" | "last" | "this")
&& matches!(unit, "week" | "month" | "year")
{
return add(
today,
match q {
"next" => 1.0,
"last" => -1.0,
_ => 0.0,
},
unit,
);
}
let (day_qualifier, day) = s
.split_once(' ')
.filter(|(q, _)| matches!(*q, "next" | "last" | "this"))
.unwrap_or(("", s));
if let Some(target) = [
"monday",
"tuesday",
"wednesday",
"thursday",
"friday",
"saturday",
"sunday",
]
.iter()
.position(|d| *d == day)
{
let offset = (target as i64 - today.weekday().num_days_from_monday() as i64).rem_euclid(7);
let delta = if day_qualifier == "last" {
if offset == 0 { -7 } else { offset - 7 }
} else if offset == 0 {
7
} else {
offset
};
return today.checked_add_signed(Duration::days(delta));
}
let (qualifier, name) = s
.split_once(' ')
.filter(|(q, _)| matches!(*q, "next" | "last" | "this"))
.unwrap_or(("", s));
let (name, year) = name
.rsplit_once(' ')
.and_then(|(n, y)| y.parse::<i32>().ok().map(|y| (n, Some(y))))
.unwrap_or((name, None));
let holiday = |name: &str, year| {
if extended {
super::holidays::extended_holiday(name, year)
} else {
super::holidays::holiday(name, year)
}
};
if let Some(d) = holiday(name, year.unwrap_or(today.year())) {
if year.is_some() {
return Some(d);
}
let delta = if qualifier == "last" {
-1
} else if qualifier == "this" {
0
} else if d < today {
1
} else {
0
};
return holiday(name, today.year() + delta);
}
for format in [
"%d %B %Y",
"%d %b %Y",
"%B %d, %Y",
"%b %d, %Y",
"%Y-%m-%d",
"%d/%m/%Y",
] {
if let Ok(d) = NaiveDate::parse_from_str(s, format) {
return Some(d);
}
}
for format in ["%d %B %Y", "%d %b %Y"] {
if let Ok(d) = NaiveDate::parse_from_str(&format!("{s} {}", today.year()), format) {
return Some(d);
}
}
if extended {
if let Some(source) = s.strip_prefix("next us federal holiday after ") {
return super::holidays::next_us_federal_holiday(date_expression(
source,
ctx,
depth + 1,
true,
)?);
}
if let Some(c) = re!(r"^(?:the )?(first|second|third|fourth|fifth|last|\d+(?:st|nd|rd|th)?) (day|business day|monday|tuesday|wednesday|thursday|friday|saturday|sunday) (in|of|after|before) (.+)$").captures(s) {
let ordinal: i32 = match &c[1] {
"first" => 1, "second" => 2, "third" => 3, "fourth" => 4, "fifth" => 5,
"last" => -1, n => n.trim_end_matches(|c: char| c.is_ascii_alphabetic()).parse().ok()?,
};
if ordinal == 0 || ordinal > 100000 { return None; }
let relative = matches!(&c[3], "after" | "before");
let (start, end) = if relative {
let d = date_expression(&c[4], ctx, depth + 1, true)?;
(d, d)
} else { period(&c[4], ctx)? };
let backwards = ordinal < 0 || &c[3] == "before";
let mut d = if backwards { end } else { start };
if relative { d = add(d, if backwards { -1.0 } else { 1.0 }, "day")?; }
let matches = |d: NaiveDate| match &c[2] {
"day" => true,
"business day" => !matches!(d.weekday(), Weekday::Sat | Weekday::Sun),
name => weekday(name) == Some(d.weekday()),
};
let mut remaining = ordinal.unsigned_abs();
while remaining > 0 {
if !relative && (d < start || d > end) { return None; }
if matches(d) { remaining -= 1; if remaining == 0 { return Some(d); } }
d = add(d, if backwards { -1.0 } else { 1.0 }, "day")?;
}
}
if let Some(c) = re!(r"^(?:the )?(monday|tuesday|wednesday|thursday|friday|saturday|sunday) (on or after|on or before|after|before) (.+)$").captures(s) {
let d = date_expression(&c[3], ctx, depth + 1, true)?;
let offset = (weekday(&c[1])?.num_days_from_monday() as i64 - d.weekday().num_days_from_monday() as i64).rem_euclid(7);
let offset = if c[2].ends_with("before") { if offset == 0 { 0 } else { offset - 7 } } else { offset };
let offset = if offset == 0 && !c[2].starts_with("on or") { if &c[2] == "before" { -7 } else { 7 } } else { offset };
return d.checked_add_signed(Duration::days(offset));
}
if let Some(c) = re!(r"^next (.+) after (.+)$").captures(s) {
let source = date_expression(&c[2], ctx, depth + 1, true)?;
for year in source.year()..=source.year().checked_add(8)? {
if let Some(d) = date_expression(&format!("{} {year}", &c[1]), ctx, depth + 1, true)
&& d > source
{
return Some(d);
}
}
return None;
}
if let Some(rest) = s
.strip_prefix("the date ")
.or_else(|| s.strip_prefix("the "))
{
return date_expression(rest, ctx, depth + 1, true);
}
}
let expression = super::syntax::word_operators(s);
if let Some((duration, source)) =
super::syntax::split_last(&expression, &[" after ", " before ", " from "])
{
let sign = if expression[duration.len()..].starts_with(" before ") {
-1.0
} else {
1.0
};
return shift(
date_expression(source, ctx, depth + 1, extended)?,
duration,
sign,
depth + 1,
extended,
);
}
if let Some((index, operator)) = super::arithmetic::operators(&expression)?
.into_iter()
.rev()
.find(|(index, operator)| {
matches!(operator, '+' | '-')
&& !(*operator == '-'
&& re!(r"\d{4}-\d{2}-\d{2}")
.find_iter(&expression)
.any(|date| *index == date.start() + 4 || *index == date.start() + 7))
})
{
let (left, right) = (&expression[..index], &expression[index + 1..]);
if let Some(source) = date_expression(left, ctx, depth + 1, extended)
&& let Some(result) = shift(
source,
right,
if operator == '+' { 1.0 } else { -1.0 },
depth + 1,
extended,
)
{
return Some(result);
}
if operator == '+'
&& (extended || !right.trim().starts_with('('))
&& let Some(source) = date_expression(right, ctx, depth + 1, extended)
&& let Some(result) = shift(source, left, 1.0, depth + 1, extended)
{
return Some(result);
}
}
None
}
fn weekday(s: &str) -> Option<Weekday> {
match s {
"monday" => Some(Weekday::Mon),
"tuesday" => Some(Weekday::Tue),
"wednesday" => Some(Weekday::Wed),
"thursday" => Some(Weekday::Thu),
"friday" => Some(Weekday::Fri),
"saturday" => Some(Weekday::Sat),
"sunday" => Some(Weekday::Sun),
_ => None,
}
}
fn ordinal_weekday_dates(
extent: &str,
first: &str,
requested: &[Weekday],
) -> Result<String, crate::Error> {
let extent = super::integer_queries::value(extent)?;
if extent <= 0.into() {
return Err(Error("invalid_duration".into()));
}
let length = extent
.to_u64()
.ok_or_else(|| Error("integer_limit".into()))?;
let first = weekday(first).ok_or_else(|| Error("invalid_endpoint".into()))?;
if requested.is_empty() {
return Err(Error("invalid_endpoint".into()));
}
let first_index = first.num_days_from_monday() as u64;
let count = (length / 7) as u128 * requested.len() as u128
+ (0..length % 7)
.filter(|offset| {
requested
.iter()
.any(|day| day.num_days_from_monday() as u64 == (first_index + offset) % 7)
})
.count() as u128;
if count > 256 {
return Err(Error("integer_limit".into()));
}
let dates = (1..=length)
.filter(|day| {
requested
.iter()
.any(|target| target.num_days_from_monday() as u64 == (first_index + day - 1) % 7)
})
.map(|day| day.to_string())
.collect::<Vec<_>>();
let result = format!(
"dates: {}; count: {}",
if dates.is_empty() {
"none".into()
} else {
dates.join(", ")
},
dates.len()
);
if result.len() > 4096 {
return Err(Error("integer_limit".into()));
}
Ok(result)
}
fn period(s: &str, ctx: &Context) -> Option<(NaiveDate, NaiveDate)> {
let year = s.parse::<i32>().ok();
let (start, next) = if let Some(year) = year {
(
NaiveDate::from_ymd_opt(year, 1, 1)?,
NaiveDate::from_ymd_opt(year.checked_add(1)?, 1, 1)?,
)
} else if s.ends_with("year") {
let year = date(s, ctx)?.year();
(
NaiveDate::from_ymd_opt(year, 1, 1)?,
NaiveDate::from_ymd_opt(year.checked_add(1)?, 1, 1)?,
)
} else {
let start = if s.ends_with("month") {
date(s, ctx)?.with_day(1)?
} else {
date(&format!("1 {s}"), ctx)?.with_day(1)?
};
(start, start.checked_add_months(Months::new(1))?)
};
Some((start, next.pred_opt()?))
}
fn shift(
source: NaiveDate,
duration: &str,
sign: f64,
depth: usize,
extended: bool,
) -> Option<NaiveDate> {
if depth > 64 {
return None;
}
let duration = super::syntax::ungroup(duration);
if !extended && duration.contains("calendar") {
return None;
}
if let Some(c) =
re!(r"^(.+?)\s*(?:calendar )?(days?|weeks?|months?|quarters?|years?|workdays?|weekdays?|business days?)$")
.captures(duration)
&& let Some(count) = if extended { super::arithmetic::eval(super::syntax::ungroup(&c[1])) } else { c[1].parse().ok() }
{
if extended && matches!(&c[2], "workday" | "workdays" | "weekday" | "weekdays" | "business day" | "business days") {
return workdays(source, count * sign, false);
}
return add(source, count * sign, &c[2]);
}
let (index, operator) = super::arithmetic::operators(duration)?
.into_iter()
.rev()
.find(|(_, operator)| matches!(operator, '+' | '-'))?;
let source = shift(source, &duration[..index], sign, depth + 1, extended)?;
shift(
source,
&duration[index + 1..],
sign * if operator == '+' { 1.0 } else { -1.0 },
depth + 1,
extended,
)
}
pub(crate) fn format_date(d: NaiveDate, ctx: &Context) -> String {
d.format(if d.year() == ctx.now.with_timezone(&ctx.timezone).year() {
"%-d %B"
} else {
"%-d %B %Y"
})
.to_string()
}
struct CalendarComponents {
days: i64,
elapsed: i64,
elapsed_millis: i64,
has_day: bool,
has_subday: bool,
fractional_day: bool,
decimal_day: bool,
}
impl CalendarComponents {
fn is_clock(&self) -> bool {
self.has_subday || self.fractional_day
}
}
fn calendar_components(input: &str) -> Option<CalendarComponents> {
let words = input.split_whitespace().collect::<Vec<_>>();
if !(2..=10).contains(&words.len()) || !words.len().is_multiple_of(2) {
return None;
}
let mut components = CalendarComponents {
days: 0,
elapsed: 0,
elapsed_millis: 0,
has_day: false,
has_subday: false,
fractional_day: false,
decimal_day: false,
};
let mut elapsed = 0.0f64;
let mut last_scale = i64::MAX;
for pair in words.as_chunks::<2>().0 {
let count = pair[0];
if !re!(r"^\d+(?:\.\d+)?$").is_match(count) {
return None;
}
let scale = match pair[1] {
"week" | "weeks" => 604_800,
"day" | "days" => 86_400,
"hour" | "hours" => 3_600,
"minute" | "minutes" => 60,
"second" | "seconds" => 1,
_ => return None,
};
if scale >= last_scale {
return None;
}
last_scale = scale;
if scale >= 86_400 {
components.decimal_day |= count.contains('.');
let effective = count.parse::<f64>().ok()?;
if !effective.is_finite() || effective >= i64::MAX as f64 {
return None;
}
let whole = if count.contains('.') {
effective.trunc() as i64
} else {
count.parse::<i64>().ok()?
};
let fraction = effective.fract();
components.fractional_day |= fraction != 0.0;
let fractional_days = fraction * (scale / 86_400) as f64;
components.days = components.days.checked_add(
whole
.checked_mul(scale / 86_400)?
.checked_add(fractional_days.floor() as i64)?,
)?;
elapsed += fractional_days.fract() * 86_400.0;
components.has_day = true;
} else {
elapsed += super::time::Time::default().seconds(&format!("{count} {}", pair[1]))?;
components.has_subday = true;
}
}
if !elapsed.is_finite() || elapsed >= i64::MAX as f64 {
return None;
}
let millis = (elapsed * 1000.0).round();
if !millis.is_finite() || millis >= i64::MAX as f64 {
return None;
}
components.elapsed = elapsed as i64;
components.elapsed_millis = millis as i64;
Some(components)
}
fn calendar_day_subday(input: &str) -> Option<(i64, i64)> {
let components = calendar_components(input)?;
(components.has_day && components.has_subday && !components.decimal_day)
.then_some((components.days, components.elapsed))
}
fn datetime(s: &str, ctx: &Context) -> Option<chrono::DateTime<chrono_tz::Tz>> {
let s = super::syntax::ungroup(s);
if let Some(&(index, operator)) = super::arithmetic::operators(s)?
.iter()
.rev()
.find(|(_, op)| "+-".contains(*op))
&& let Some(seconds) = super::time::Time::default().seconds(&s[index + 1..])
{
return datetime(&s[..index], ctx)?.checked_add_signed(Duration::try_milliseconds(
(seconds * 1000.0 * if operator == '+' { 1.0 } else { -1.0 }) as i64,
)?);
}
let normalized = re!(r"^(\d{4}-\d{2}-\d{2}) ((?:\d|noon|midnight).+)$").replace(s, "$1 at $2");
let s = normalized.as_ref();
let (day, clock) = if super::time::clock(s).is_some() {
("today", s)
} else {
s.split_once(" at ").unwrap_or((s, "midnight"))
};
let d = date(day, ctx)?;
let seconds = super::time::clock(clock)?;
ctx.timezone
.from_local_datetime(&d.and_hms_opt(
(seconds / 3600) as u32,
(seconds % 3600 / 60) as u32,
(seconds % 60) as u32,
)?)
.earliest()
}
fn full_datetime(d: chrono::DateTime<chrono_tz::Tz>) -> String {
format!(
"{} at {}:{:02}{} {}",
d.format("%-d %B %Y"),
if d.hour().is_multiple_of(12) {
12
} else {
d.hour() % 12
},
d.minute(),
if d.second() == 0 {
String::new()
} else {
format!(":{:02}", d.second())
},
if d.hour() < 12 { "am" } else { "pm" }
)
}
fn days_in_month(d: NaiveDate) -> Option<u32> {
let next = d.with_day(1)?.checked_add_months(Months::new(1))?;
Some(next.pred_opt()?.day())
}
pub(crate) fn add(d: NaiveDate, n: f64, unit: &str) -> Option<NaiveDate> {
if !n.is_finite() {
return None;
}
match unit {
"day" | "days" => d.checked_add_signed(Duration::try_days(n as i64)?),
"week" | "weeks" => d.checked_add_signed(Duration::try_days((n * 7.0) as i64)?),
"month" | "months" | "quarter" | "quarters" | "year" | "years" => {
let n = if unit.starts_with("year") {
n * 12.0
} else if unit.starts_with("quarter") {
n * 3.0
} else {
n
};
if n.abs() > 1000000.0 {
return None;
}
let count = n.abs().trunc() as u32;
let d = if n >= 0.0 {
d.checked_add_months(Months::new(count))?
} else {
d.checked_sub_months(Months::new(count))?
};
d.checked_add_signed(Duration::try_days(
(n.fract() * days_in_month(d)? as f64) as i64,
)?)
}
"workday" | "workdays" | "weekday" | "weekdays" | "business day" | "business days" => {
workdays(d, n, true)
}
_ => None,
}
}
pub(crate) fn workdays(mut d: NaiveDate, n: f64, count_source: bool) -> Option<NaiveDate> {
if !n.is_finite() || n.abs() > 100000.0 {
return None;
}
let mut remaining = n.abs() as u64;
while remaining > 0 {
let next = d.checked_add_signed(Duration::days(if n >= 0.0 { 1 } else { -1 }))?;
let counted = if n < 0.0 && count_source { d } else { next };
if !matches!(counted.weekday(), Weekday::Sat | Weekday::Sun) {
remaining -= 1;
}
d = next;
}
Some(d)
}
pub(crate) fn interval(a: NaiveDate, b: NaiveDate, unit: &str) -> i64 {
let days = b.signed_duration_since(a).num_days();
match unit {
"hour" | "hours" => days * 24,
"minute" | "minutes" => days * 1440,
"second" | "seconds" => days * 86400,
"week" | "weeks" => days / 7,
"year" | "years" => {
if b < a {
return -interval(b, a, unit);
}
i64::from(b.year() - a.year() - i32::from((b.month(), b.day()) < (a.month(), a.day())))
}
"month" | "months" => {
if b < a {
return -interval(b, a, unit);
}
let mut months = (b.year() - a.year()) * 12 + b.month() as i32 - a.month() as i32;
if a.checked_add_months(Months::new(months as u32))
.is_some_and(|d| d > b)
{
months -= 1;
}
months as i64
}
"business days" | "workdays" => {
if days.abs() > 100000 {
return 0;
}
let mut count = 0;
let mut d = a;
for _ in 0..days.unsigned_abs() {
d += Duration::days(days.signum());
if !matches!(d.weekday(), Weekday::Sat | Weekday::Sun) {
count += days.signum();
}
}
count
}
_ => days,
}
}
impl Plugin for Calendar {
fn evaluate(&self, input: &str, ctx: &Context) -> Outcome {
self.evaluate_input(input, ctx, false)
}
}
impl Calendar {
pub(crate) fn evaluate_expression(&self, input: &str, ctx: &Context) -> Outcome {
if let Some((left, _)) = super::syntax::split_last(input, &[" / ", " * "])
&& date_expression(left, ctx, 0, true).is_some()
{
return Some(Err(Error("invalid_expression".into())));
}
self.evaluate_input(input, ctx, true)
}
fn evaluate_input(&self, input: &str, ctx: &Context, extended: bool) -> Outcome {
let date = |s: &str, ctx: &Context| date_expression(s, ctx, 0, extended);
let mut s = input.trim().to_lowercase();
if !extended {
if let Some(c) = re!(r"^(\d{4}-\d{2}-\d{2}-[\d.]+)([a-z]+)$").captures(&s)
&& let Some(unit) = super::units::Units::default().unit(&c[2])
&& let Some(value) = super::arithmetic::eval(&c[1])
{
return Some(Ok(super::units::format_quantity(value, &unit)));
}
let expression = super::syntax::ungroup(&s);
if let Some((left, right)) = super::syntax::split_last(expression, &[" + ", " - "])
&& date(left, ctx).is_some()
{
if let Some(c) = re!(r"^\((.+)\) (days?|weeks?|months?|years?)$").captures(right)
&& let Some(n) = super::arithmetic::eval(&c[1])
{
let unit = super::units::Units::default().unit(&c[2])?;
return Some(Ok(super::units::format_quantity(n, &unit)));
}
if right.starts_with('(')
&& re!(r"\b(?:months?|years?)\b").is_match(right)
&& !right.contains("calendar")
&& let Some(seconds) = super::time::Time::default()
.seconds(&super::syntax::ungroup(right).replace(" - ", " -"))
{
let sign = if expression[left.len()..].starts_with(" - ") {
-1.0
} else {
1.0
};
let local = datetime(left, ctx)?
.naive_local()
.checked_add_signed(Duration::try_seconds((seconds * sign) as i64)?)?;
return Some(Ok(full_datetime(
ctx.timezone.from_local_datetime(&local).earliest()?,
)));
}
if right.starts_with('(') && right.contains("calendar") {
let duration = re!(r"\bcalendar (?:months?|years?|weeks?)\b")
.replace_all(super::syntax::ungroup(right), "days");
let seconds = super::time::Time::default().seconds(&duration)?;
let sign = if expression[left.len()..].starts_with(" - ") {
-1.0
} else {
1.0
};
return Some(Ok(format_date(
add(date(left, ctx)?, seconds / 86400.0 * sign, "days")?,
ctx,
)));
}
if let Some(quantity) = super::units::Units::default().quantity(right)
&& quantity.unit.dimension != [0, 0, 1, 0, 0, 0, 0, 0]
{
let sign = if expression[left.len()..].starts_with(" - ") {
-1.0
} else {
1.0
};
return Some(Ok(super::units::format_quantity(
(quantity.base / quantity.unit.scale - quantity.unit.offset) * sign,
&quantity.unit,
)));
}
if right.trim_start().starts_with('(')
&& let Some(Ok(duration)) =
super::compositions::standard_grouped_comments(right)
&& let Some(days) = super::arithmetic::eval(&duration)
{
let sign = if expression[left.len()..].starts_with(" - ") {
-1.0
} else {
1.0
};
return Some(Ok(format_date(
add(date(left, ctx)?, days * sign, "days")?,
ctx,
)));
}
}
if let Some((left, right)) = super::syntax::split_last(expression, &[" + "])
&& right.trim().starts_with('(')
&& date(right, ctx).is_some()
&& super::time::Time::default()
.seconds(super::syntax::ungroup(left))
.is_some()
{
return Some(Err(Error("null_result".into())));
}
if let Some((source, unit)) = super::syntax::split_last(expression, &[" in "])
&& matches!(unit, "days" | "weeks" | "months" | "years")
&& date(source, ctx).is_some()
{
return Some(Err(Error("null_result".into())));
}
}
if extended {
let ordinal = super::syntax::ungroup(&s);
if let Some(c) = re!(r"^a calendar has (.+?) days, with day 1 on a ([a-z]+)\. list the dates that fall on ([a-z]+) and give their count\.?$").captures(ordinal) {
let day = c[3].trim_end_matches('s');
let requested = weekday(day).ok_or_else(|| Error("invalid_endpoint".into()));
return Some(requested.and_then(|day| ordinal_weekday_dates(&c[1], &c[2], &[day])));
}
if let Some(c) = re!(r"^in a (.+?)-day month whose first day is ([a-z]+), list every date that is a weekend day and count the weekend dates\.?$").captures(ordinal) {
return Some(ordinal_weekday_dates(&c[1], &c[2], &[Weekday::Sat, Weekday::Sun]));
}
if matches!(
s.as_str(),
"weekdays in week" | "workdays in week" | "business days in week"
) {
return Some(Ok(format!("5 {}", s.trim_end_matches(" in week"))));
}
if let Some(c) = re!(r"^duration between (.+) and (.+)$").captures(&s) {
return Some(Ok(super::time::span(
(date(&c[2], ctx)? - date(&c[1], ctx)?).num_seconds() as f64,
604800.0,
)));
}
if let Some(c) = re!(r"^leap year (\d{4})$").captures(&s) {
return Some(Ok(NaiveDate::from_ymd_opt(c[1].parse().ok()?, 2, 29)
.is_some()
.to_string()));
}
if let Some(c) = re!(r"^(weekdays|workdays|business days|mondays|tuesdays|wednesdays|thursdays|fridays|saturdays|sundays) in (.+)$").captures(&s) {
let (mut d, end) = period(&c[2], ctx)?;
let mut n = 0;
while d <= end {
if if let Some(day) = weekday(c[1].trim_end_matches('s')) { d.weekday() == day }
else { !matches!(d.weekday(), Weekday::Sat | Weekday::Sun) } { n += 1; }
d = d.succ_opt()?;
}
return Some(Ok(format!("{n} {}", if n == 1 { c[1].trim_end_matches('s') } else { &c[1] })));
}
}
if let Some((prefix, window)) = s.rsplit_once(" from ")
&& prefix.contains(" per ")
&& let Some((start, end)) = super::syntax::split_last(window, &[" to ", " through "])
{
if window.contains(" through ") {
let a = datetime(start, ctx)?.date_naive();
let b = datetime(end, ctx)?.date_naive().succ_opt()?;
return Some(Ok(super::time::span(
(b - a).num_seconds() as f64,
604800.0,
)));
}
let (a, b) = (datetime(start, ctx)?, datetime(end, ctx)?);
return Some(Ok(super::time::span(
(b - a).num_seconds() as f64,
604800.0,
)));
}
for (word, n) in [
("one", 1),
("two", 2),
("three", 3),
("four", 4),
("five", 5),
("six", 6),
("seven", 7),
("eight", 8),
("nine", 9),
("ten", 10),
] {
if let Some(rest) = s.strip_prefix(&format!("{word} ")) {
s = format!("{n} {rest}");
break;
}
}
if let Some(c) = re!(r"^(\d{1,4})-(\d{1,2})-(\d{1,2}) (.+) ago$").captures(&s) {
let today = date("today", ctx)?;
let mut year = c[1].parse::<i32>().ok()?;
if c[1].len() <= 2 {
year += 2000;
}
let base = today.with_year(today.year() - year)?;
let base = add(
add(base, -c[2].parse::<f64>().ok()?, "months")?,
-c[3].parse::<f64>().ok()?,
"days",
)?;
let seconds = super::time::Time::default().seconds(&c[4])?;
let day = format!(
"{} {} {}",
base.day(),
base.format("%B"),
if base.year() > 0 {
base.year()
} else {
1 - base.year()
}
);
if !c[4].contains("hour") && !c[4].contains("minute") && !c[4].contains("second") {
return Some(Ok(day));
}
let h = (seconds as u32 / 3600) % 24;
let m = (seconds as u32 % 3600) / 60;
return Some(Ok(format!(
"{day} at {}:{m:02} {}",
if h.is_multiple_of(12) { 12 } else { h % 12 },
if h < 12 { "am" } else { "pm" }
)));
}
if let Some((a, b)) = s.split_once(" to ")
&& chrono::DateTime::parse_from_rfc3339(a).is_ok()
&& chrono::DateTime::parse_from_rfc3339(b).is_ok()
{
return Some(Err(Error("null_result".into())));
}
if matches!(s.as_str(), "current timestamp" | "new timestamp") {
return Some(Ok(format!(
"{:.6}",
ctx.now.timestamp_micros() as f64 / 1e6
)
.trim_end_matches('0')
.trim_end_matches('.')
.into()));
}
if s == "date now" {
return Some(Ok(format_date(date("today", ctx)?, ctx)));
}
let s = if let Some(c) =
re!(r"^time in (.+?) ([+-]?[\d.]+ .+ (?:after|before) .+ at .+)$").captures(&s)
{
super::time::zone(&c[1])?;
c[2].to_string()
} else {
s
};
if let Some(c) = re!(r"^(.+) (after|before|from) (.+ at .+)$").captures(&s) {
let base = datetime(&c[3], ctx)?;
let seconds = super::time::Time::default().seconds(&c[1])?
* if &c[2] == "before" { -1.0 } else { 1.0 };
let result = base.checked_add_signed(Duration::try_seconds(seconds as i64)?)?;
return Some(Ok(full_datetime(result)));
}
let s = if let Some(c) = re!(r"^(.+) ago in (.+)$").captures(&s) {
format!("time in {} {} ago", &c[2], &c[1])
} else {
s
};
if let Some(c) =
re!(r"^(?:time in (.+?) )?([+-]?[\d.]+ .+?) ago(?: at (.+))?$").captures(&s)
{
let seconds = super::time::Time::default().seconds(&c[2]);
if let Some(seconds) = seconds {
let target = if let Some(name) = c.get(1) {
super::time::zone(name.as_str())?
} else {
ctx.timezone
};
let start = ctx.now.with_timezone(&target);
let zoned_components = (c.get(1).is_some() && c.get(3).is_none())
.then(|| calendar_components(&c[2]))
.flatten();
let mut time = if let Some(components) = &zoned_components {
let local = ctx.now.with_timezone(&ctx.timezone);
let shifted = if components.days == 0 {
local
} else {
let date = local
.date_naive()
.checked_sub_signed(Duration::try_days(components.days)?)?;
super::time::standard_local_datetime(
date.and_time(local.time()),
ctx.timezone,
)?
};
shifted
.checked_sub_signed(Duration::try_milliseconds(components.elapsed_millis)?)?
.with_timezone(&target)
} else if c.get(1).is_none() && c.get(3).is_some() {
if let Some((days, subday)) = calendar_day_subday(&c[2]) {
let date = start
.date_naive()
.checked_sub_signed(Duration::try_days(days)?)?;
super::time::standard_local_datetime(date.and_time(start.time()), target)?
.checked_sub_signed(Duration::try_seconds(subday)?)?
} else {
start.checked_sub_signed(Duration::try_seconds(seconds as i64)?)?
}
} else {
start.checked_sub_signed(Duration::try_seconds(seconds as i64)?)?
};
if let Some(clock) = c.get(3) {
let seconds = super::time::clock(clock.as_str())?;
time = target
.from_local_datetime(&time.date_naive().and_hms_opt(
(seconds / 3600) as u32,
(seconds % 3600 / 60) as u32,
0,
)?)
.earliest()?;
}
let clock_result = zoned_components.as_ref().map(CalendarComponents::is_clock);
if clock_result == Some(false)
|| (clock_result.is_none()
&& c.get(3).is_none()
&& seconds >= 86400.0
&& !re!(r"months?|years?").is_match(&c[2]))
{
return Some(Ok(format_date(time.date_naive(), ctx)));
}
if clock_result == Some(true) || c.get(3).is_some() || seconds < 86400.0 {
let reference = ctx.now.with_timezone(&target).date_naive();
if clock_result == Some(true)
&& !(-1..=1).contains(
&time
.date_naive()
.signed_duration_since(reference)
.num_days(),
)
{
return Some(Ok(full_datetime(time)));
}
return Some(Ok(super::time::clock_relative(
time.date_naive(),
time.time().num_seconds_from_midnight() as i64,
ctx.now.with_timezone(&target).date_naive(),
false,
)));
}
}
}
if let Some(c) = re!(r"^time in (.+?) (.+) from (.+)$").captures(&s) {
let zone = super::time::zone(&c[1])?;
let time = datetime(&c[3], ctx)?
+ Duration::try_seconds(super::time::Time::default().seconds(&c[2])? as i64)?;
return Some(Ok(format_date(time.with_timezone(&zone).date_naive(), ctx)));
}
if let Some(c) = re!(r"^(days|weeks|months|years) (?:left|remaining) in (.+)$").captures(&s)
{
let Ok(year) = c[2].parse::<i32>() else {
return Some(Err(Error("null_result".into())));
};
let today = date("today", ctx)?;
let end = NaiveDate::from_ymd_opt(year + 1, 1, 1)?;
let count = interval(today, end, &c[1]).max(0);
return Some(Ok(format!(
"{} {}",
count,
if count == 1 {
c[1].trim_end_matches('s')
} else {
&c[1]
}
)));
}
if let Some(c) = re!(r"^(hours|minutes|seconds) in (.+) to (.+)$").captures(&s) {
let delta = if let (Some(a), Some(b)) = (datetime(&c[2], ctx), datetime(&c[3], ctx)) {
(b - a).num_seconds()
} else {
super::time::clock(&c[3])? - super::time::clock(&c[2])?
};
let units = super::units::Units::default();
let u = units.unit(&c[1])?;
return Some(Ok(super::units::format_quantity(
delta as f64 / u.scale,
&u,
)));
}
if let Some(c) = re!(r"^days in q([1-4]) (\d{4})$").captures(&s) {
let year = c[2].parse().ok()?;
let month = c[1].parse::<u32>().ok()? * 3 - 2;
let a = NaiveDate::from_ymd_opt(year, month, 1)?;
let b = a.checked_add_months(Months::new(3))?;
return Some(Ok(format!("{} days", (b - a).num_days())));
}
if re!(r"^(next|last|this) (month|year)$").is_match(&s) {
let d = date(&s, ctx)?;
return Some(Ok(d
.format(if s.ends_with("month") { "%B" } else { "%Y" })
.to_string()));
}
if let Some(c) = re!(r"^(?:from )?(.+) (to|until|till|through) (.+)$").captures(&s)
&& let (Some(mut a), Some(mut b)) = (date(&c[1], ctx), date(&c[3], ctx))
{
if &c[2] == "through" {
b = b.succ_opt()?;
}
if &c[2] != "through" && b < a {
std::mem::swap(&mut a, &mut b);
}
let months = interval(a, b, "months");
if months > 0 && &c[2] != "through" {
let mut parts = vec![];
for (n, unit) in [(months / 12, "year"), (months % 12, "month")] {
if n > 0 {
parts.push(format!("{n} {unit}{}", if n == 1 { "" } else { "s" }));
}
}
let rest = (b - add(a, months as f64, "months")?).num_seconds();
if rest > 0 {
parts.push(super::time::span(rest as f64, 604800.0));
}
return Some(Ok(parts.join(" ")));
}
return Some(Ok(super::time::span(
(b - a).num_seconds() as f64,
604800.0,
)));
}
if s == "now" || s == "time now" {
let time = ctx.now.with_timezone(&ctx.timezone);
return Some(Ok(format!(
"{}:{:02} {}",
if time.hour().is_multiple_of(12) {
12
} else {
time.hour() % 12
},
time.minute(),
if time.hour() < 12 { "am" } else { "pm" }
)));
}
if let Some(c) = re!(r"^days in ([a-z]+) (\d{4})$").captures(&s) {
let d = date(&format!("1 {} {}", &c[1], &c[2]), ctx)?;
return Some(Ok(format!("{} days", days_in_month(d)?)));
}
if [
"monday",
"tuesday",
"wednesday",
"thursday",
"friday",
"saturday",
"sunday",
]
.contains(&s.as_str())
{
let mut out = s.clone();
out[..1].make_ascii_uppercase();
return Some(Ok(out));
}
if let Some(c) = re!(r"^([\d.]+) (days?|weeks?|months?|years?) ago$").captures(&s) {
return Some(Ok(format_date(
add(date("today", ctx)?, -c[1].parse::<f64>().ok()?, &c[2])?,
ctx,
)));
}
if let Some(c) = re!(r"^(week number|week of year|week of month|day number|day of (?:the )?year|day of (?:the )?month)(?: (?:on )?(.+))?$").captures(&s) {
let d = date(c.get(2).map(|m|m.as_str()).unwrap_or("today"),ctx)?;
let n = match &c[1] {
"week number" | "week of year" => d.iso_week().week(),
"week of month" => { let first=d.with_day(1)?.weekday().num_days_from_monday(); (d.day()-1+first)/7+u32::from(first<4) },
"day number" | "day of year" | "day of the year" => d.ordinal(),
_ => d.day(),
};
return Some(Ok(n.to_string()));
}
if let Some(c) =
re!(r"^(days|weeks|months|years|hours|minutes|seconds) in (.+)$").captures(&s)
{
let raw = &c[2];
let year = raw.parse::<i32>().ok().filter(|y| *y >= 1000);
let month = date(&format!("1 {raw}"), ctx);
let days = if let Some(y) = year {
(NaiveDate::from_ymd_opt(y + 1, 1, 1)? - NaiveDate::from_ymd_opt(y, 1, 1)?)
.num_days() as f64
} else if let Some(d) = month {
days_in_month(d)? as f64
} else {
0.0
};
if days > 0.0 {
let units = super::units::Units::default();
let u = units.unit(&c[1])?;
return Some(Ok(super::units::format_quantity(
days * 86400.0 / u.scale,
&u,
)));
}
if date(raw, ctx).is_some() {
return Some(Err(Error("null_result".into())));
}
}
if let Some(c) = re!(r"^(days|weeks|months|years) since (.+)$").captures(&s) {
let today = date("today", ctx)?;
let mut d = date(&c[2], ctx)?;
if extended
&& let Some(current) = super::holidays::extended_holiday(&c[2], today.year())
{
d = if current <= today {
current
} else {
super::holidays::extended_holiday(&c[2], today.year() - 1)?
};
} else if d > today && super::holidays::holiday(&c[2], today.year()).is_some() {
d = super::holidays::holiday(&c[2], today.year() - 1)?;
}
let n = interval(d, today, &c[1]);
return Some(Ok(format!(
"{} {}",
n,
if n == 1 {
c[1].trim_end_matches('s')
} else {
&c[1]
}
)));
}
let pattern = re!(
r"^([+-]?[\d.]+) (days?|weeks?|months?|years?|workdays?|weekdays?|business days?) (after|before|from) (.+)$"
);
if let Some(c) = pattern.captures(&s) {
let n = c[1].parse::<f64>().ok()? * if &c[3] == "before" { -1.0 } else { 1.0 };
let source = date(&c[4], ctx)?;
let result = shift(source, &format!("{n} {}", &c[2]), 1.0, 0, extended)?;
if &c[4] == "now" {
let time = ctx.now.with_timezone(&ctx.timezone);
return Some(Ok(format!(
"{} at {}:{:02} {}",
result.format("%-d %B %Y"),
if time.hour().is_multiple_of(12) {
12
} else {
time.hour() % 12
},
time.minute(),
if time.hour() < 12 { "am" } else { "pm" }
)));
}
return Some(Ok(
if source.year() != ctx.now.with_timezone(&ctx.timezone).year() {
result.format("%-d %B %Y").to_string()
} else {
format_date(result, ctx)
},
));
}
if (!s.contains('/') || re!(r"/\d{4}$").is_match(&s))
&& let Some(d) = date(&s, ctx)
{
return Some(Ok(format_date(d, ctx)));
}
let difference = super::syntax::split_last(&s, &[" in "]);
let (expression, unit) = difference.unwrap_or((&s, ""));
if (unit.is_empty() || matches!(unit, "days" | "weeks" | "months" | "years"))
&& let Some((left, right)) =
super::syntax::split_last(super::syntax::ungroup(expression), &[" - ", " minus "])
&& let (Some(a), Some(b)) = (date(left, ctx), date(right, ctx))
{
if unit.is_empty() {
return Some(Ok(super::time::span(
if extended {
(a - b).num_seconds() as f64
} else {
(a - b).num_seconds().abs() as f64
},
604800.0,
)));
}
let n = interval(b, a, unit);
return Some(Ok(format!(
"{n} {}",
if n.abs() == 1 {
unit.trim_end_matches('s')
} else {
unit
}
)));
}
if let Some(c) =
re!(r"^(.+) to (.+) in (days|weeks|months|years|hours|minutes|seconds)$").captures(&s)
{
return self.evaluate(&format!("{} from {} to {}", &c[3], &c[1], &c[2]), ctx);
}
let pattern = re!(
r"^(days|weeks|months|years|hours|minutes|seconds|business days|workdays) (?:between|from|in) (.+) (and|to|through|until|−|-) (.+)$"
);
if let Some(c) = pattern.captures(&s) {
let endpoints = (date(&c[2], ctx), date(&c[4], ctx));
let (Some(a), Some(mut b)) = endpoints else {
return if extended {
Some(Err(Error("invalid_expression".into())))
} else {
None
};
};
if &c[3] == "through" {
b = b.succ_opt()?;
}
let n = if extended && matches!(&c[1], "business days" | "workdays") {
if b < a {
-interval(b.pred_opt()?, a.pred_opt()?, "workdays")
} else {
interval(a.pred_opt()?, b.pred_opt()?, "workdays")
}
} else if !extended && &c[1] == "business days" && b < a {
0
} else {
interval(a, b, &c[1])
};
let unit = if &c[1] == "business days" {
"workdays"
} else {
&c[1]
};
return Some(Ok(format!(
"{} {}",
number(n as f64),
if n.abs() == 1 {
unit.trim_end_matches('s')
} else {
unit
}
)));
}
if let Some(c) =
re!(r"^difference between (.+) and (.+) in (days|weeks|months|years)$").captures(&s)
{
let n = interval(date(&c[2], ctx)?, date(&c[1], ctx)?, &c[3]);
return Some(Ok(format!(
"{} {}",
number(n as f64),
if n.abs() == 1 {
c[3].trim_end_matches('s')
} else {
&c[3]
}
)));
}
if let Some(c) = re!(r"^(?:midpoint|halfway) between (.+) and (.+)$").captures(&s) {
let a = datetime(&c[1], ctx)?;
let b = datetime(&c[2], ctx)?;
let mid = a + (b - a) / 2;
return Some(Ok(if c[1].contains(" at ") {
full_datetime(mid)
} else {
format_date(mid.date_naive(), ctx)
}));
}
if let Some(c) = re!(r"^(.+) day of (?:the )?week$").captures(&s) {
return Some(Ok(date(&c[1], ctx)?.format("%A").to_string()));
}
if let Some(c) = re!(r"^day of (?:the )?week (?:on )?(.+)$").captures(&s) {
if !extended && c[1].starts_with('(') {
return Some(Err(Error("null_result".into())));
}
return Some(Ok(date(&c[1], ctx)?.format("%A").to_string()));
}
if let Some(c) =
re!(r"^(days|weeks|months|years|hours|minutes|seconds) (?:until|till|to|before) (.+)$")
.captures(&s)
{
let now = ctx.now.with_timezone(&ctx.timezone);
if let Some(raw) = c[2].strip_suffix('!')
&& date(raw, ctx).is_some()
{
return Some(Err(Error("internal_error".into())));
}
let end = date(&c[2], ctx)?;
if end < now.date_naive() {
return Some(Err(Error("null_result".into())));
}
let days = interval(now.date_naive(), end, "days") as f64;
let units = super::units::Units::default();
let u = units.unit(&c[1])?;
let seconds = if matches!(&c[1], "hours" | "minutes" | "seconds") {
(datetime(&c[2], ctx)? - now).num_seconds() as f64
} else if matches!(&c[1], "months" | "years") {
let whole = interval(now.date_naive(), end, &c[1]);
let base = add(now.date_naive(), whole as f64, &c[1])?;
let base_midnight = base.and_hms_opt(0, 0, 0)?;
let base_offset = ctx
.timezone
.from_local_datetime(&base.and_time(now.time()))
.earliest()
.or_else(|| {
(!extended)
.then(|| ctx.timezone.from_local_datetime(&base_midnight).earliest())
.flatten()
})?
.offset()
.fix();
let midnight = base_offset
.from_local_datetime(&base.and_hms_opt(0, 0, 0)?)
.earliest()?;
whole as f64 * u.scale
+ datetime(&c[2], ctx)?
.signed_duration_since(midnight)
.num_seconds() as f64
} else {
days * 86400.0
};
return Some(Ok(super::units::format_quantity(seconds / u.scale, &u)));
}
None
}
}