Skip to main content

faker_rust/default/
time.rs

1//! Time generator - generates random dates and times
2
3use crate::config::FakerConfig;
4use chrono::{DateTime, Duration, Utc};
5// Removed unused Rng
6
7/// Generate a random date/time between two given dates
8pub fn between(from: DateTime<Utc>, to: DateTime<Utc>) -> DateTime<Utc> {
9    let config = FakerConfig::current();
10    let from_ts = from.timestamp();
11    let to_ts = to.timestamp();
12
13    if from_ts >= to_ts {
14        return from;
15    }
16
17    let ts = config.rand_range_i64(from_ts, to_ts);
18    DateTime::from_timestamp(ts, 0).unwrap_or(from)
19}
20
21/// Generate a random date/time in the past (up to given number of days)
22pub fn backward(days: i64) -> DateTime<Utc> {
23    let now = Utc::now();
24    let from = now - Duration::days(days);
25    between(from, now)
26}
27
28/// Generate a random date/time in the future (up to given number of days)
29pub fn forward(days: i64) -> DateTime<Utc> {
30    let now = Utc::now();
31    let to = now + Duration::days(days);
32    between(now, to)
33}
34
35#[cfg(test)]
36mod tests {
37    use super::*;
38
39    #[test]
40    fn test_between() {
41        let from = Utc::now() - Duration::days(10);
42        let to = Utc::now();
43        let result = between(from, to);
44        assert!(result >= from && result <= to);
45    }
46}