Skip to main content

reltime/
lib.rs

1//! Relative time representations with language support.
2//!
3//! This library provides types for expressing dates and times in human-readable forms,
4//! supporting both absolute and relative representations. All types serialise to and from
5//! JSON in a natural format.
6//!
7//! # Features
8//!
9//! - `swedish` (default): Enables Swedish language variants for all time types.
10
11use chrono::{DateTime, Months, NaiveTime, Utc};
12use derive_more::Display;
13use schemars::JsonSchema;
14use serde::{Deserialize, Serialize};
15
16use crate::{
17    exact::ExactDateTime,
18    language::Language,
19    month::{
20        April, August, December, February, January, July, June, March, May, Month, November,
21        October, September,
22    },
23    relative::{Relative, ThisMonth, ThisWeek, Today, Tomorrow},
24    traits::FromLanguage,
25    weekday::{Friday, Monday, Saturday, Sunday, Thursday, Tuesday, Wednesday, Weekday},
26};
27
28pub mod exact;
29pub mod language;
30pub mod month;
31pub mod relative;
32pub mod traits;
33pub mod weekday;
34
35/// A time representation supporting relative, named, exact, and absolute forms.
36///
37/// Serialises as an untagged enum, allowing natural JSON representations like
38/// `"Today"`, `"Monday"`, `"2025-07-29T10:30:05Z"`, etc.
39#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Display)]
40#[serde(untagged)]
41pub enum Time {
42    Relative(Relative),
43    Weekday(Weekday),
44    Month(Month),
45    Exact(ExactDateTime),
46    DateTime(DateTime<Utc>),
47}
48
49impl Time {
50    /// Converts to the earliest possible timestamp, relative to the current time.
51    pub fn to_chrono_min_now(self) -> DateTime<Utc> {
52        self.to_chrono_min(Utc::now())
53    }
54
55    /// Converts to the earliest possible timestamp, relative to the given time.
56    pub fn to_chrono_min(self, relative_to: DateTime<Utc>) -> DateTime<Utc> {
57        match self {
58            Time::Relative(relative) => relative.to_chrono_min(relative_to),
59            Time::Weekday(weekday) => weekday.to_chrono_min(relative_to, true),
60            Time::Month(month) => month
61                .to_chrono_max(relative_to, true)
62                .checked_sub_months(Months::new(1))
63                .unwrap(),
64            Time::Exact(exact) => exact.to_chrono_min(relative_to),
65            Time::DateTime(date_time) => date_time,
66        }
67    }
68
69    /// Converts to the latest possible timestamp, relative to the current time.
70    pub fn to_chrono_max_now(self) -> DateTime<Utc> {
71        self.to_chrono_max(Utc::now())
72    }
73
74    /// Converts to the latest possible timestamp, relative to the given time.
75    pub fn to_chrono_max(self, relative_to: DateTime<Utc>) -> DateTime<Utc> {
76        match self {
77            Time::Relative(relative) => relative.to_chrono_max(relative_to),
78            Time::Weekday(weekday) => weekday.to_chrono_max(relative_to, true),
79            Time::Month(month) => month.to_chrono_max(relative_to, true),
80            Time::Exact(exact) => exact.to_chrono_max(relative_to),
81            Time::DateTime(date_time) => date_time,
82        }
83    }
84
85    /// Converts a chrono timestamp to the most natural time representation.
86    ///
87    /// When `relative_to` is provided, attempts to express the timestamp as a relative
88    /// or named time (e.g., "Today", "Monday") in the specified language.
89    pub fn from_max_chrono(
90        date_time: DateTime<Utc>,
91        relative_to: Option<DateTime<Utc>>,
92        language: Language,
93    ) -> Time {
94        if let Some(now) = relative_to
95            && date_time.time() == NaiveTime::MIN
96        {
97            let today = Relative::Today(Today::from_language(language));
98            if date_time == today.clone().to_chrono_max(now) {
99                return Time::Relative(today);
100            };
101
102            let tomorrow = Relative::Tomorrow(Tomorrow::from_language(language));
103            if date_time == tomorrow.clone().to_chrono_max(now) {
104                return Time::Relative(tomorrow);
105            }
106
107            let monday = Time::Weekday(Weekday::Monday(Monday::from_language(language)));
108            if date_time == monday.clone().to_chrono_max(now) {
109                return monday;
110            }
111
112            let tuesday = Time::Weekday(Weekday::Tuesday(Tuesday::from_language(language)));
113            if date_time == tuesday.clone().to_chrono_max(now) {
114                return tuesday;
115            }
116
117            let wednesday = Time::Weekday(Weekday::Wednesday(Wednesday::from_language(language)));
118            if date_time == wednesday.clone().to_chrono_max(now) {
119                return wednesday;
120            }
121
122            let thursday = Time::Weekday(Weekday::Thursday(Thursday::from_language(language)));
123            if date_time == thursday.clone().to_chrono_max(now) {
124                return thursday;
125            }
126
127            let friday = Time::Weekday(Weekday::Friday(Friday::from_language(language)));
128            if date_time == friday.clone().to_chrono_max(now) {
129                return friday;
130            }
131
132            let saturday = Time::Weekday(Weekday::Saturday(Saturday::from_language(language)));
133            if date_time == saturday.clone().to_chrono_max(now) {
134                return saturday;
135            }
136
137            let sunday = Time::Weekday(Weekday::Sunday(Sunday::from_language(language)));
138            if date_time == sunday.clone().to_chrono_max(now) {
139                return sunday;
140            }
141
142            let january = Time::Month(Month::January(January::from_language(language)));
143            if date_time == january.clone().to_chrono_max(now) {
144                return january;
145            }
146
147            let february = Time::Month(Month::February(February::from_language(language)));
148            if date_time == february.clone().to_chrono_max(now) {
149                return february;
150            }
151
152            let march = Time::Month(Month::March(March::from_language(language)));
153            if date_time == march.clone().to_chrono_max(now) {
154                return march;
155            }
156
157            let april = Time::Month(Month::April(April::from_language(language)));
158            if date_time == april.clone().to_chrono_max(now) {
159                return april;
160            }
161
162            let may = Time::Month(Month::May(May::from_language(language)));
163            if date_time == may.clone().to_chrono_max(now) {
164                return may;
165            }
166
167            let june = Time::Month(Month::June(June::from_language(language)));
168            if date_time == june.clone().to_chrono_max(now) {
169                return june;
170            }
171
172            let july = Time::Month(Month::July(July::from_language(language)));
173            if date_time == july.clone().to_chrono_max(now) {
174                return july;
175            }
176
177            let august = Time::Month(Month::August(August::from_language(language)));
178            if date_time == august.clone().to_chrono_max(now) {
179                return august;
180            }
181
182            let september = Time::Month(Month::September(September::from_language(language)));
183            if date_time == september.clone().to_chrono_max(now) {
184                return september;
185            }
186
187            let october = Time::Month(Month::October(October::from_language(language)));
188            if date_time == october.clone().to_chrono_max(now) {
189                return october;
190            }
191
192            let november = Time::Month(Month::November(November::from_language(language)));
193            if date_time == november.clone().to_chrono_max(now) {
194                return november;
195            }
196
197            let december = Time::Month(Month::December(December::from_language(language)));
198            if date_time == december.clone().to_chrono_max(now) {
199                return december;
200            }
201
202            let this_week = Relative::ThisWeek(ThisWeek::from_language(language));
203            if date_time == this_week.clone().to_chrono_max(now) {
204                return Time::Relative(this_week);
205            }
206
207            let this_month = Relative::ThisMonth(ThisMonth::from_language(language));
208            if date_time == this_month.clone().to_chrono_max(now) {
209                return Time::Relative(this_month);
210            }
211        }
212
213        Time::DateTime(date_time)
214    }
215}
216
217#[cfg(test)]
218mod tests {
219    use chrono::{Datelike, Days};
220
221    use super::*;
222
223    /// Creates a DateTime\<Utc> for Tuesday July 29th, 2025 at 10:30:05.
224    fn base_time() -> DateTime<Utc> {
225        DateTime::parse_from_rfc3339("2025-07-29T10:30:05-00:00")
226            .unwrap()
227            .to_utc()
228    }
229
230    #[test]
231    fn weekday_next_midnight() {
232        let tuesday = base_time();
233
234        let weekday = Weekday::from_chrono(tuesday, false, Language::default());
235
236        assert_eq!(weekday, Weekday::tuesday());
237
238        let midnight_tomorrow = weekday.to_chrono_max(tuesday, false);
239
240        assert_eq!(
241            midnight_tomorrow,
242            tuesday
243                .checked_add_days(Days::new(1))
244                .unwrap()
245                .with_time(NaiveTime::MIN)
246                .unwrap()
247        );
248    }
249
250    #[test]
251    fn weekday_next_midnight_skipping_self() {
252        let tuesday = base_time();
253
254        let tuesday_as_weekday = Weekday::from_chrono(tuesday, false, Language::default());
255
256        assert_eq!(tuesday_as_weekday, Weekday::tuesday());
257
258        let midnight_next_wednesday = tuesday_as_weekday.to_chrono_max(tuesday, true);
259
260        assert_eq!(
261            midnight_next_wednesday,
262            tuesday
263                .checked_add_days(Days::new(8))
264                .unwrap()
265                .with_time(NaiveTime::MIN)
266                .unwrap()
267        );
268    }
269
270    #[test]
271    fn midnight_tomorrow_means_today() {
272        let tuesday = base_time();
273
274        let midnight_tomorrow = tuesday
275            .checked_add_days(Days::new(1))
276            .unwrap()
277            .with_time(NaiveTime::MIN)
278            .unwrap();
279
280        let time = Time::from_max_chrono(midnight_tomorrow, Some(tuesday), Language::default());
281
282        assert_eq!(time, Time::Relative(Relative::today()));
283    }
284
285    #[test]
286    fn midnight_in_two_days_means_tomorrow() {
287        let tuesday = base_time();
288
289        let midnight_in_two_days = tuesday
290            .checked_add_days(Days::new(2))
291            .unwrap()
292            .with_time(NaiveTime::MIN)
293            .unwrap();
294
295        let time = Time::from_max_chrono(midnight_in_two_days, Some(tuesday), Language::default());
296
297        assert_eq!(time, Time::Relative(Relative::tomorrow()));
298    }
299
300    #[test]
301    fn weekday_chrono_min() {
302        let tuesday = base_time();
303
304        let tuesday_as_weekday = Weekday::from_chrono(tuesday, false, Language::default());
305
306        assert_eq!(tuesday_as_weekday, Weekday::tuesday());
307
308        let tuesday_as_weekday_min = tuesday_as_weekday.to_chrono_min(tuesday, false);
309
310        let tuesday_min = tuesday;
311
312        assert_eq!(tuesday_min, tuesday_as_weekday_min);
313    }
314
315    #[test]
316    fn weekday_chrono_min_skipping_self() {
317        let tuesday = base_time();
318
319        let tuesday_as_weekday = Weekday::from_chrono(tuesday, false, Language::default());
320
321        assert_eq!(tuesday_as_weekday, Weekday::tuesday());
322
323        let next_tuesday_as_weekday_min = tuesday_as_weekday.to_chrono_min(tuesday, true);
324
325        let next_tuesday_min = tuesday
326            .checked_add_days(Days::new(7))
327            .unwrap()
328            .with_time(NaiveTime::MIN)
329            .unwrap();
330
331        assert_eq!(next_tuesday_min, next_tuesday_as_weekday_min);
332    }
333
334    #[test]
335    fn weekday_chrono_max() {
336        let tuesday = base_time();
337
338        let tuesday_as_weekday = Weekday::from_chrono(tuesday, false, Language::default());
339
340        assert_eq!(tuesday_as_weekday, Weekday::tuesday());
341
342        let tuesday_as_weekday_max = tuesday_as_weekday.to_chrono_max(tuesday, false);
343
344        let tuesday_max = tuesday
345            .checked_add_days(Days::new(1))
346            .unwrap()
347            .with_time(NaiveTime::MIN)
348            .unwrap();
349
350        assert_eq!(tuesday_max, tuesday_as_weekday_max);
351    }
352
353    #[test]
354    fn weekday_chrono_max_skipping_self() {
355        let tuesday = base_time();
356
357        let tuesday_as_weekday = Weekday::from_chrono(tuesday, false, Language::default());
358
359        assert_eq!(tuesday_as_weekday, Weekday::tuesday());
360
361        let tuesday_as_weekday_max = tuesday_as_weekday.to_chrono_max(tuesday, true);
362
363        let tuesday_max = tuesday
364            .checked_add_days(Days::new(8))
365            .unwrap()
366            .with_time(NaiveTime::MIN)
367            .unwrap();
368
369        assert_eq!(tuesday_max, tuesday_as_weekday_max);
370    }
371
372    #[test]
373    fn midnight_next_monday_means_sunday() {
374        let tuesday = base_time();
375
376        dbg!(&tuesday);
377        let midnight_next_monday = tuesday
378            .checked_add_days(Days::new(6))
379            .unwrap()
380            .with_time(NaiveTime::MIN)
381            .unwrap();
382
383        dbg!(&midnight_next_monday);
384
385        assert_eq!(
386            midnight_next_monday.weekday(),
387            chrono::Weekday::Mon,
388            "chrono monday check"
389        );
390
391        let time = Time::from_max_chrono(midnight_next_monday, Some(tuesday), Language::default());
392
393        println!(
394            "sunday chrono max {}",
395            Time::Weekday(Weekday::sunday()).to_chrono_max(tuesday)
396        );
397
398        assert_eq!(time, Time::Weekday(Weekday::sunday()));
399    }
400
401    #[test]
402    fn month_conversions() {
403        let tuesday = base_time(); // July 29th, 2025
404
405        let july = Month::from_chrono(tuesday, false, Language::default());
406        assert_eq!(july, Month::july());
407
408        // Next occurrence of July should be midnight on August 1st
409        let next_july = july.to_chrono_max(tuesday, false);
410        assert_eq!(next_july.month(), 8);
411        assert_eq!(next_july.day(), 1);
412    }
413
414    #[test]
415    fn month_skipping_self() {
416        let tuesday = base_time(); // July 29th, 2025
417
418        let july = Month::july();
419
420        // Skipping self should give us next year's July
421        let next_july = july.to_chrono_max(tuesday, true);
422        assert_eq!(next_july.year(), 2026);
423        assert_eq!(next_july.month(), 8);
424        assert_eq!(next_july.day(), 1);
425    }
426
427    #[test]
428    fn relative_today_conversion() {
429        let tuesday = base_time();
430
431        let today = Relative::today();
432
433        // Min should be start of today
434        let min = today.clone().to_chrono_min(tuesday);
435        assert_eq!(min.date_naive(), tuesday.date_naive());
436        assert_eq!(min.time(), NaiveTime::MIN);
437
438        // Max should be start of tomorrow
439        let max = today.to_chrono_max(tuesday);
440        assert_eq!(max, tuesday.checked_add_days(Days::new(1)).unwrap().with_time(NaiveTime::MIN).unwrap());
441    }
442
443    #[test]
444    fn relative_tomorrow_conversion() {
445        let tuesday = base_time();
446
447        let tomorrow = Relative::tomorrow();
448
449        // Min should be start of tomorrow
450        let min = tomorrow.clone().to_chrono_min(tuesday);
451        assert_eq!(min, tuesday.checked_add_days(Days::new(1)).unwrap().with_time(NaiveTime::MIN).unwrap());
452
453        // Max should be start of day after tomorrow
454        let max = tomorrow.to_chrono_max(tuesday);
455        assert_eq!(max, tuesday.checked_add_days(Days::new(2)).unwrap().with_time(NaiveTime::MIN).unwrap());
456    }
457
458    #[test]
459    #[cfg(feature = "swedish")]
460    fn language_switching_weekday() {
461        use crate::traits::WithLanguage;
462        use crate::language::{Language, Swedish};
463
464        let monday_english = Monday::default();
465        assert_eq!(format!("{}", monday_english), "Monday");
466
467        let monday_swedish = monday_english.with_language(Language::Swedish(Swedish::default()));
468        assert_eq!(format!("{}", monday_swedish), "MÃ¥ndag");
469    }
470
471    #[test]
472    #[cfg(feature = "swedish")]
473    fn language_switching_month() {
474        use crate::traits::WithLanguage;
475        use crate::language::{Language, Swedish};
476
477        let january_english = January::default();
478        assert_eq!(format!("{}", january_english), "January");
479
480        let january_swedish = january_english.with_language(Language::Swedish(Swedish::default()));
481        assert_eq!(format!("{}", january_swedish), "Januari");
482    }
483
484    #[test]
485    #[cfg(feature = "swedish")]
486    fn language_switching_relative() {
487        use crate::traits::WithLanguage;
488        use crate::language::{Language, Swedish};
489
490        let today_english = Today::default();
491        assert_eq!(format!("{}", today_english), "Today");
492
493        let today_swedish = today_english.with_language(Language::Swedish(Swedish::default()));
494        assert_eq!(format!("{}", today_swedish), "Idag");
495    }
496
497    #[test]
498    fn this_week_conversion() {
499        let tuesday = base_time(); // July 29th, 2025
500
501        let this_week = Relative::this_week();
502
503        // This week should end on Sunday midnight (which is the next Monday)
504        let max = this_week.to_chrono_max(tuesday);
505
506        // Should be the upcoming Sunday at midnight (which shows as Monday)
507        assert_eq!(max.weekday(), chrono::Weekday::Mon);
508    }
509
510    #[test]
511    fn next_week_conversion() {
512        let tuesday = base_time();
513
514        let next_week = Relative::next_week();
515
516        // Next week should end a week after this week ends
517        let max = next_week.to_chrono_max(tuesday);
518
519        // Should be Monday, 7 days after the end of this week
520        assert_eq!(max.weekday(), chrono::Weekday::Mon);
521
522        let this_week_max = Relative::this_week().to_chrono_max(tuesday);
523        assert_eq!(max, this_week_max.checked_add_days(Days::new(7)).unwrap());
524    }
525
526    #[test]
527    fn this_month_conversion() {
528        let tuesday = base_time(); // July 29th, 2025
529
530        let this_month = Relative::this_month();
531
532        // This month should end at midnight on August 1st
533        let max = this_month.to_chrono_max(tuesday);
534        assert_eq!(max.month(), 8);
535        assert_eq!(max.day(), 1);
536        assert_eq!(max.year(), 2025);
537    }
538
539    #[test]
540    fn month_year_boundary() {
541        let dec_15 = DateTime::parse_from_rfc3339("2025-12-15T10:00:00-00:00")
542            .unwrap()
543            .to_utc();
544
545        // December should wrap to January next year
546        let december = Month::december();
547        let max = december.to_chrono_max(dec_15, false);
548
549        assert_eq!(max.year(), 2026);
550        assert_eq!(max.month(), 1);
551        assert_eq!(max.day(), 1);
552    }
553
554    #[test]
555    fn month_january_in_december() {
556        let dec_15 = DateTime::parse_from_rfc3339("2025-12-15T10:00:00-00:00")
557            .unwrap()
558            .to_utc();
559
560        // January should be next year when we're in December
561        let january = Month::january();
562        let max = january.to_chrono_max(dec_15, false);
563
564        assert_eq!(max.year(), 2026);
565        assert_eq!(max.month(), 2);
566        assert_eq!(max.day(), 1);
567    }
568
569    #[test]
570    fn weekday_year_boundary() {
571        // Test on December 31, 2025 (Wednesday)
572        let wed_dec_31 = DateTime::parse_from_rfc3339("2025-12-31T10:00:00-00:00")
573            .unwrap()
574            .to_utc();
575
576        // Monday should be next year
577        let monday = Weekday::monday();
578        let max = monday.to_chrono_max(wed_dec_31, false);
579
580        assert_eq!(max.year(), 2026);
581        assert_eq!(max.month(), 1);
582    }
583
584    #[test]
585    fn from_max_chrono_preserves_language() {
586        let tuesday = base_time();
587        let midnight_tomorrow = tuesday
588            .checked_add_days(Days::new(1))
589            .unwrap()
590            .with_time(NaiveTime::MIN)
591            .unwrap();
592
593        #[cfg(feature = "swedish")]
594        {
595            use crate::language::{Language, Swedish};
596
597            let time = Time::from_max_chrono(
598                midnight_tomorrow,
599                Some(tuesday),
600                Language::Swedish(Swedish::default()),
601            );
602
603            if let Time::Relative(Relative::Today(today)) = time {
604                assert_eq!(format!("{}", today), "Idag");
605            } else {
606                panic!("Expected Today variant");
607            }
608        }
609
610        #[cfg(not(feature = "swedish"))]
611        {
612            let time = Time::from_max_chrono(midnight_tomorrow, Some(tuesday), Language::default());
613
614            if let Time::Relative(Relative::Today(today)) = time {
615                assert_eq!(format!("{}", today), "Today");
616            } else {
617                panic!("Expected Today variant");
618            }
619        }
620    }
621}