faker_rust/default/
date.rs1use chrono::{Duration, NaiveDate, Utc};
4
5pub fn backward(days: Option<i64>, _from: Option<&str>, _to: Option<&str>) -> String {
7 let days_back = days.unwrap_or(365);
8 let today = Utc::now().date_naive();
9 let target = today - Duration::try_days(days_back).unwrap();
10 target.format("%Y-%m-%d").to_string()
11}
12
13pub fn forward(days: Option<i64>, _from: Option<&str>, _to: Option<&str>) -> String {
15 let days_forward = days.unwrap_or(365);
16 let today = Utc::now().date_naive();
17 let target = today + Duration::try_days(days_forward).unwrap();
18 target.format("%Y-%m-%d").to_string()
19}
20
21pub fn between(from: &str, to: &str) -> String {
23 let start =
24 NaiveDate::parse_from_str(from, "%Y-%m-%d").unwrap_or_else(|_| Utc::now().date_naive());
25 let end = NaiveDate::parse_from_str(to, "%Y-%m-%d").unwrap_or_else(|_| Utc::now().date_naive());
26
27 let config = crate::config::FakerConfig::current();
28 let range = (end - start).num_days();
29 if range <= 0 {
30 return from.to_string();
31 }
32
33 let days_offset = config.rand_range(0, range as u32) as i64;
34 let target = start + Duration::try_days(days_offset).unwrap();
35 target.format("%Y-%m-%d").to_string()
36}
37
38pub fn birthday(min_age: Option<i32>, max_age: Option<i32>) -> String {
40 let config = crate::config::FakerConfig::current();
41 let min = min_age.unwrap_or(18) as u32;
42 let max = max_age.unwrap_or(65) as u32;
43 let age = config.rand_range(min, max);
44
45 let today = Utc::now().date_naive();
46 let days_in_year = 365;
47
48 let year = today.format("%Y").to_string().parse::<i32>().unwrap() - age as i32;
50 let day_of_year = config.rand_range(1, days_in_year as u32) as i64;
51
52 let base_date = NaiveDate::from_ymd_opt(year, 1, 1).unwrap_or(today);
53 let target = base_date + Duration::try_days(day_of_year - 1).unwrap();
54
55 target.format("%Y-%m-%d").to_string()
56}
57
58pub fn in_date_period(start_date: &str, end_date: &str, _format: Option<&str>) -> String {
60 between(start_date, end_date)
61}
62
63pub fn on_day_of_week_between(_day_of_week: &str, from: &str, to: &str) -> String {
65 between(from, to)
67}