use chrono::{
DateTime, Datelike, MappedLocalTime, NaiveDateTime, NaiveTime, Offset, TimeDelta, TimeZone,
};
use crate::lang;
pub fn parse<Tz: TimeZone>(input: &str, now: DateTime<Tz>) -> Result<i32, String> {
let wrong = || {
lang::f(
"Send times are like 18:30, 2026-12-31 09:00 or +45 minutes, not \"{input}\"",
&[("input", &input)],
)
};
let past = || lang::t("That time has already passed").to_string();
let input = input.trim();
let zone = now.timezone();
let local = |at: NaiveDateTime| moment(&zone, at).ok_or_else(wrong);
let when = if let Some(minutes) = input.strip_prefix('+') {
let minutes: i64 = minutes.trim().parse().map_err(|_| wrong())?;
if minutes < 1 {
return Err(wrong());
}
TimeDelta::try_minutes(minutes)
.and_then(|later| now.clone().checked_add_signed(later))
.ok_or_else(wrong)?
} else if let Ok(time) = NaiveTime::parse_from_str(input, "%H:%M") {
let today = local(now.date_naive().and_time(time))?;
if today > now {
today
} else {
local((now.date_naive() + TimeDelta::days(1)).and_time(time))?
}
} else {
let moment = NaiveDateTime::parse_from_str(input, "%Y-%m-%d %H:%M").map_err(|_| wrong())?;
local(moment)?
};
if when <= now {
return Err(past());
}
if when.clone().signed_duration_since(now) > TimeDelta::days(365) {
return Err(lang::t("Telegram schedules messages at most a year ahead").into());
}
i32::try_from(when.timestamp()).map_err(|_| wrong())
}
pub fn moment<Tz: TimeZone>(zone: &Tz, at: NaiveDateTime) -> Option<DateTime<Tz>> {
match zone.from_local_datetime(&at) {
MappedLocalTime::None => {
let before = zone
.from_local_datetime(&(at - TimeDelta::hours(3)))
.earliest()?;
let offset = before.offset().fix().local_minus_utc();
let utc = at.checked_sub_signed(TimeDelta::seconds(offset.into()))?;
Some(zone.from_utc_datetime(&utc))
}
found => found.earliest(),
}
}
pub fn describe<Tz: TimeZone>(at: i32, now: &DateTime<Tz>) -> String {
let Some(at) = now.timezone().timestamp_opt(at.into(), 0).single() else {
return String::new();
};
let (at, today) = (at.naive_local(), now.naive_local().date());
let time = at.format("%H:%M");
if at.date() == today {
time.to_string()
} else if at.year() == today.year() {
format!("{} {time}", lang::day_month(&at))
} else {
format!("{} {time}", lang::day_month_year(&at))
}
}
#[cfg(test)]
mod tests {
use chrono::{FixedOffset, Local, NaiveDate};
use super::*;
#[test]
fn a_scheduled_time_is_named_by_its_time_of_day_and_its_date_when_not_today() {
let zone = FixedOffset::east_opt(3600).unwrap();
let now = zone.with_ymd_and_hms(2026, 12, 4, 10, 0, 0).unwrap();
let at = |d, h, m| {
zone.with_ymd_and_hms(2026, 12, d, h, m, 0)
.unwrap()
.timestamp() as i32
};
assert_eq!(describe(at(4, 18, 30), &now), "18:30");
assert_eq!(describe(at(5, 9, 5), &now), "5 Dec 09:05");
let next_year = zone
.with_ymd_and_hms(2027, 1, 2, 8, 0, 0)
.unwrap()
.timestamp() as i32;
assert_eq!(describe(next_year, &now), "2 Jan 2027 08:00");
}
#[derive(Clone, Copy)]
struct Spring;
fn spring_change() -> NaiveDateTime {
NaiveDate::from_ymd_opt(2026, 3, 29)
.unwrap()
.and_hms_opt(2, 0, 0)
.unwrap()
}
fn east(hours: i32) -> FixedOffset {
FixedOffset::east_opt(hours * 3600).unwrap()
}
impl TimeZone for Spring {
type Offset = FixedOffset;
fn from_offset(_: &FixedOffset) -> Self {
Spring
}
fn offset_from_local_date(&self, _: &NaiveDate) -> MappedLocalTime<FixedOffset> {
unreachable!("only date-times are asked")
}
fn offset_from_local_datetime(
&self,
local: &NaiveDateTime,
) -> MappedLocalTime<FixedOffset> {
if *local < spring_change() {
MappedLocalTime::Single(east(1))
} else if *local < spring_change() + TimeDelta::hours(1) {
MappedLocalTime::None
} else {
MappedLocalTime::Single(east(2))
}
}
fn offset_from_utc_date(&self, _: &NaiveDate) -> FixedOffset {
unreachable!("only date-times are asked")
}
fn offset_from_utc_datetime(&self, utc: &NaiveDateTime) -> FixedOffset {
if *utc < spring_change() - TimeDelta::hours(1) {
east(1)
} else {
east(2)
}
}
}
#[test]
fn a_time_the_clocks_skip_is_read_as_before_they_went_forward() {
let evening = Spring
.with_ymd_and_hms(2026, 3, 28, 22, 0, 0)
.single()
.unwrap();
let meant = Spring
.with_ymd_and_hms(2026, 3, 29, 3, 30, 0)
.single()
.unwrap()
.timestamp() as i32;
assert_eq!(parse("02:30", evening), Ok(meant));
assert_eq!(parse("2026-03-29 02:30", evening), Ok(meant));
let at = |h| {
Spring
.with_ymd_and_hms(2026, 3, 29, h, 0, 0)
.single()
.unwrap()
.timestamp() as i32
};
assert_eq!(parse("01:00", evening), Ok(at(1)));
assert_eq!(parse("03:00", evening), Ok(at(3)));
}
fn now() -> DateTime<Local> {
Local
.with_ymd_and_hms(2026, 11, 28, 12, 0, 0)
.single()
.unwrap()
}
fn shown(at: i32) -> (i32, u32, u32, u32, u32) {
use chrono::Datelike;
use chrono::Timelike;
let at = Local.timestamp_opt(at as i64, 0).single().unwrap();
(at.year(), at.month(), at.day(), at.hour(), at.minute())
}
#[test]
fn a_clock_time_later_today_is_today() {
let at = parse("18:30", now()).unwrap();
assert_eq!(shown(at), (2026, 11, 28, 18, 30));
}
#[test]
fn a_clock_time_already_past_is_tomorrow() {
let at = parse("09:00", now()).unwrap();
assert_eq!(shown(at), (2026, 11, 29, 9, 0));
}
#[test]
fn a_clock_time_of_this_minute_counts_as_past() {
let at = parse("12:00", now()).unwrap();
assert_eq!(shown(at), (2026, 11, 29, 12, 0));
}
#[test]
fn a_full_date_and_time_is_that_moment() {
let at = parse("2026-12-31 09:00", now()).unwrap();
assert_eq!(shown(at), (2026, 12, 31, 9, 0));
}
#[test]
fn a_full_date_and_time_already_past_is_an_error() {
assert_eq!(
parse("2026-11-28 11:59", now()),
Err(lang::t("That time has already passed").to_string())
);
assert!(parse("2020-01-01 00:00", now()).is_err());
}
#[test]
fn telegram_schedules_at_most_a_year_ahead() {
let too_late = lang::t("Telegram schedules messages at most a year ahead").to_string();
assert!(parse("+525600", now()).is_ok(), "365 days");
assert_eq!(parse("+525601", now()), Err(too_late.clone()));
assert_eq!(parse("2028-01-01 09:00", now()), Err(too_late));
}
#[test]
fn minutes_from_now() {
assert_eq!(
parse("+45", now()).unwrap(),
(now() + TimeDelta::minutes(45)).timestamp() as i32
);
assert_eq!(
parse("+1", now()).unwrap(),
(now() + TimeDelta::minutes(1)).timestamp() as i32
);
}
#[test]
fn anything_else_is_an_error() {
for input in [
"",
"+",
"+0",
"+-5",
"+1.5",
"25:00",
"12:60",
"2026-13-01 10:00",
"soon",
"18:30:00",
"+999999999999999",
"+9223372036854775807",
"+52560000",
] {
assert!(parse(input, now()).is_err(), "{input:?}");
}
}
}