format_distance.rs

  1// This won't be documented further as it is intended to be removed, or merged with the `time_format` crate.
  2
  3use chrono::{DateTime, Local, NaiveDateTime};
  4
  5#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
  6pub enum DateTimeType {
  7    Naive(NaiveDateTime),
  8    Local(DateTime<Local>),
  9}
 10
 11impl DateTimeType {
 12    /// Converts the [`DateTimeType`] to a [`NaiveDateTime`].
 13    ///
 14    /// If the [`DateTimeType`] is already a [`NaiveDateTime`], it will be returned as is.
 15    /// If the [`DateTimeType`] is a [`DateTime<Local>`], it will be converted to a [`NaiveDateTime`].
 16    pub fn to_naive(self) -> NaiveDateTime {
 17        match self {
 18            DateTimeType::Naive(naive) => naive,
 19            DateTimeType::Local(local) => local.naive_local(),
 20        }
 21    }
 22}
 23
 24pub struct FormatDistance {
 25    date: DateTimeType,
 26    base_date: DateTimeType,
 27    include_seconds: bool,
 28    add_suffix: bool,
 29    hide_prefix: bool,
 30}
 31
 32impl FormatDistance {
 33    pub const fn new(date: DateTimeType, base_date: DateTimeType) -> Self {
 34        Self {
 35            date,
 36            base_date,
 37            include_seconds: false,
 38            add_suffix: false,
 39            hide_prefix: false,
 40        }
 41    }
 42
 43    pub fn from_now(date: DateTimeType) -> Self {
 44        Self::new(date, DateTimeType::Local(Local::now()))
 45    }
 46
 47    pub const fn include_seconds(mut self, include_seconds: bool) -> Self {
 48        self.include_seconds = include_seconds;
 49        self
 50    }
 51
 52    pub const fn add_suffix(mut self, add_suffix: bool) -> Self {
 53        self.add_suffix = add_suffix;
 54        self
 55    }
 56
 57    pub const fn hide_prefix(mut self, hide_prefix: bool) -> Self {
 58        self.hide_prefix = hide_prefix;
 59        self
 60    }
 61}
 62
 63impl std::fmt::Display for FormatDistance {
 64    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 65        write!(
 66            f,
 67            "{}",
 68            format_distance(
 69                self.date,
 70                self.base_date.to_naive(),
 71                self.include_seconds,
 72                self.add_suffix,
 73                self.hide_prefix,
 74            )
 75        )
 76    }
 77}
 78/// Calculates the distance in seconds between two [`NaiveDateTime`] objects.
 79/// It returns a signed integer denoting the difference. If `date` is earlier than `base_date`, the returned value will be negative.
 80///
 81/// ## Arguments
 82///
 83/// * `date` - A [NaiveDateTime`] object representing the date of interest
 84/// * `base_date` - A [NaiveDateTime`] object representing the base date against which the comparison is made
 85const fn distance_in_seconds(date: NaiveDateTime, base_date: NaiveDateTime) -> i64 {
 86    let duration = date.signed_duration_since(base_date);
 87    -duration.num_seconds()
 88}
 89
 90/// Generates a string describing the time distance between two dates in a human-readable way.
 91fn distance_string(
 92    distance: i64,
 93    include_seconds: bool,
 94    add_suffix: bool,
 95    hide_prefix: bool,
 96) -> String {
 97    let suffix = if distance < 0 { " from now" } else { " ago" };
 98
 99    let distance = distance.abs();
100
101    let minutes = distance / 60;
102    let hours = distance / 3_600;
103    let days = distance / 86_400;
104    let months = distance / 2_592_000;
105
106    let string = if distance < 5 && include_seconds {
107        if hide_prefix {
108            "5 seconds"
109        } else {
110            "less than 5 seconds"
111        }
112        .to_string()
113    } else if distance < 10 && include_seconds {
114        if hide_prefix {
115            "10 seconds"
116        } else {
117            "less than 10 seconds"
118        }
119        .to_string()
120    } else if distance < 20 && include_seconds {
121        if hide_prefix {
122            "20 seconds"
123        } else {
124            "less than 20 seconds"
125        }
126        .to_string()
127    } else if distance < 40 && include_seconds {
128        "half a minute".to_string()
129    } else if distance < 60 && include_seconds {
130        if hide_prefix {
131            "a minute"
132        } else {
133            "less than a minute"
134        }
135        .to_string()
136    } else if distance < 90 && include_seconds {
137        "1 minute".to_string()
138    } else if distance < 30 {
139        if hide_prefix {
140            "a minute"
141        } else {
142            "less than a minute"
143        }
144        .to_string()
145    } else if distance < 90 {
146        "1 minute".to_string()
147    } else if distance < 2_700 {
148        format!("{} minutes", minutes)
149    } else if distance < 5_400 {
150        if hide_prefix {
151            "1 hour"
152        } else {
153            "about 1 hour"
154        }
155        .to_string()
156    } else if distance < 86_400 {
157        if hide_prefix {
158            format!("{} hours", hours)
159        } else {
160            format!("about {} hours", hours)
161        }
162    } else if distance < 172_800 {
163        "1 day".to_string()
164    } else if distance < 2_592_000 {
165        format!("{} days", days)
166    } else if distance < 5_184_000 {
167        if hide_prefix {
168            "1 month"
169        } else {
170            "about 1 month"
171        }
172        .to_string()
173    } else if distance < 7_776_000 {
174        if hide_prefix {
175            "2 months"
176        } else {
177            "about 2 months"
178        }
179        .to_string()
180    } else if distance < 31_540_000 {
181        format!("{} months", months)
182    } else if distance < 39_425_000 {
183        if hide_prefix {
184            "1 year"
185        } else {
186            "about 1 year"
187        }
188        .to_string()
189    } else if distance < 55_195_000 {
190        if hide_prefix { "1 year" } else { "over 1 year" }.to_string()
191    } else if distance < 63_080_000 {
192        if hide_prefix {
193            "2 years"
194        } else {
195            "almost 2 years"
196        }
197        .to_string()
198    } else {
199        let years = distance / 31_536_000;
200        let remaining_months = (distance % 31_536_000) / 2_592_000;
201
202        if remaining_months < 3 {
203            if hide_prefix {
204                format!("{} years", years)
205            } else {
206                format!("about {} years", years)
207            }
208        } else if remaining_months < 9 {
209            if hide_prefix {
210                format!("{} years", years)
211            } else {
212                format!("over {} years", years)
213            }
214        } else if hide_prefix {
215            format!("{} years", years + 1)
216        } else {
217            format!("almost {} years", years + 1)
218        }
219    };
220
221    if add_suffix {
222        format!("{}{}", string, suffix)
223    } else {
224        string
225    }
226}
227
228/// Get the time difference between two dates into a relative human readable string.
229///
230/// For example, "less than a minute ago", "about 2 hours ago", "3 months from now", etc.
231///
232/// Use [`format_distance_from_now`] to compare a NaiveDateTime against now.
233pub fn format_distance(
234    date: DateTimeType,
235    base_date: NaiveDateTime,
236    include_seconds: bool,
237    add_suffix: bool,
238    hide_prefix: bool,
239) -> String {
240    let distance = distance_in_seconds(date.to_naive(), base_date);
241
242    distance_string(distance, include_seconds, add_suffix, hide_prefix)
243}
244
245/// Get the time difference between a date and now as relative human readable string.
246///
247/// For example, "less than a minute ago", "about 2 hours ago", "3 months from now", etc.
248pub fn format_distance_from_now(
249    datetime: DateTimeType,
250    include_seconds: bool,
251    add_suffix: bool,
252    hide_prefix: bool,
253) -> String {
254    let now = chrono::offset::Local::now().naive_local();
255
256    format_distance(datetime, now, include_seconds, add_suffix, hide_prefix)
257}
258
259#[cfg(test)]
260mod tests {
261    use super::*;
262    use chrono::NaiveDateTime;
263
264    #[test]
265    fn test_format_distance() {
266        let date = DateTimeType::Naive(
267            #[allow(deprecated)]
268            NaiveDateTime::from_timestamp_opt(9600, 0).expect("Invalid NaiveDateTime for date"),
269        );
270        let base_date = DateTimeType::Naive(
271            #[allow(deprecated)]
272            NaiveDateTime::from_timestamp_opt(0, 0).expect("Invalid NaiveDateTime for base_date"),
273        );
274
275        assert_eq!(
276            "about 2 hours",
277            format_distance(date, base_date.to_naive(), false, false, false)
278        );
279    }
280
281    #[test]
282    fn test_format_distance_with_suffix() {
283        let date = DateTimeType::Naive(
284            #[allow(deprecated)]
285            NaiveDateTime::from_timestamp_opt(9600, 0).expect("Invalid NaiveDateTime for date"),
286        );
287        let base_date = DateTimeType::Naive(
288            #[allow(deprecated)]
289            NaiveDateTime::from_timestamp_opt(0, 0).expect("Invalid NaiveDateTime for base_date"),
290        );
291
292        assert_eq!(
293            "about 2 hours from now",
294            format_distance(date, base_date.to_naive(), false, true, false)
295        );
296    }
297
298    #[test]
299    fn test_format_distance_from_hms() {
300        let date = DateTimeType::Naive(
301            NaiveDateTime::parse_from_str("1969-07-20T11:22:33Z", "%Y-%m-%dT%H:%M:%SZ")
302                .expect("Invalid NaiveDateTime for date"),
303        );
304        let base_date = DateTimeType::Naive(
305            NaiveDateTime::parse_from_str("2024-02-01T00:00:00Z", "%Y-%m-%dT%H:%M:%SZ")
306                .expect("Invalid NaiveDateTime for base_date"),
307        );
308
309        assert_eq!(
310            "over 54 years ago",
311            format_distance(date, base_date.to_naive(), false, true, false)
312        );
313    }
314
315    #[test]
316    fn test_format_distance_string() {
317        assert_eq!(
318            distance_string(3, false, false, false),
319            "less than a minute"
320        );
321        assert_eq!(
322            distance_string(7, false, false, false),
323            "less than a minute"
324        );
325        assert_eq!(
326            distance_string(13, false, false, false),
327            "less than a minute"
328        );
329        assert_eq!(
330            distance_string(21, false, false, false),
331            "less than a minute"
332        );
333        assert_eq!(distance_string(45, false, false, false), "1 minute");
334        assert_eq!(distance_string(61, false, false, false), "1 minute");
335        assert_eq!(distance_string(1920, false, false, false), "32 minutes");
336        assert_eq!(distance_string(3902, false, false, false), "about 1 hour");
337        assert_eq!(distance_string(18002, false, false, false), "about 5 hours");
338        assert_eq!(distance_string(86470, false, false, false), "1 day");
339        assert_eq!(distance_string(345880, false, false, false), "4 days");
340        assert_eq!(
341            distance_string(2764800, false, false, false),
342            "about 1 month"
343        );
344        assert_eq!(
345            distance_string(5184000, false, false, false),
346            "about 2 months"
347        );
348        assert_eq!(distance_string(10368000, false, false, false), "4 months");
349        assert_eq!(
350            distance_string(34694000, false, false, false),
351            "about 1 year"
352        );
353        assert_eq!(
354            distance_string(47310000, false, false, false),
355            "over 1 year"
356        );
357        assert_eq!(
358            distance_string(61503000, false, false, false),
359            "almost 2 years"
360        );
361        assert_eq!(
362            distance_string(160854000, false, false, false),
363            "about 5 years"
364        );
365        assert_eq!(
366            distance_string(236550000, false, false, false),
367            "over 7 years"
368        );
369        assert_eq!(
370            distance_string(249166000, false, false, false),
371            "almost 8 years"
372        );
373    }
374
375    #[test]
376    fn test_format_distance_string_include_seconds() {
377        assert_eq!(
378            distance_string(3, true, false, false),
379            "less than 5 seconds"
380        );
381        assert_eq!(
382            distance_string(7, true, false, false),
383            "less than 10 seconds"
384        );
385        assert_eq!(
386            distance_string(13, true, false, false),
387            "less than 20 seconds"
388        );
389        assert_eq!(distance_string(21, true, false, false), "half a minute");
390        assert_eq!(
391            distance_string(45, true, false, false),
392            "less than a minute"
393        );
394        assert_eq!(distance_string(61, true, false, false), "1 minute");
395    }
396}