|
| 1 | +use std::fmt; |
| 2 | + |
| 3 | +#[derive(Debug)] |
| 4 | +struct JalaliDate { |
| 5 | + year: usize, |
| 6 | + month: usize, |
| 7 | + day: usize, |
| 8 | +} |
| 9 | +impl fmt::Display for JalaliDate { |
| 10 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 11 | + write!(f, "{:04}-{:02}-{:02}", self.year, self.month, self.day) |
| 12 | + } |
| 13 | +} |
| 14 | + |
| 15 | +fn gregorian_to_jalali(year: usize, month: usize, day: usize) -> JalaliDate { |
| 16 | + let mut result = JalaliDate { |
| 17 | + year: 0, |
| 18 | + month: 0, |
| 19 | + day: 0, |
| 20 | + }; |
| 21 | + |
| 22 | + let days_of_greg_month = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]; |
| 23 | + |
| 24 | + let (adjusted_year, initial_year) = if year <= 1600 { |
| 25 | + (year - 621, 0) |
| 26 | + } else { |
| 27 | + (year - 1600, 979) |
| 28 | + }; |
| 29 | + |
| 30 | + result.year = initial_year; |
| 31 | + |
| 32 | + let temp = if adjusted_year > 2 { |
| 33 | + adjusted_year + 1 |
| 34 | + } else { |
| 35 | + adjusted_year |
| 36 | + }; |
| 37 | + |
| 38 | + let mut days = ((temp + 3) / 4) + (365 * adjusted_year) - ((temp + 99) / 100) - 80 |
| 39 | + + days_of_greg_month[month - 1] |
| 40 | + + ((temp + 399) / 400) |
| 41 | + + day; |
| 42 | + |
| 43 | + result.year += 33 * (days / 12053); |
| 44 | + days %= 12053; |
| 45 | + |
| 46 | + result.year += 4 * (days / 1461); |
| 47 | + days %= 1461; |
| 48 | + |
| 49 | + if days > 365 { |
| 50 | + result.year += (days - 1) / 365; |
| 51 | + days = (days - 1) % 365; |
| 52 | + } |
| 53 | + |
| 54 | + result.month = if days < 186 { |
| 55 | + 1 + (days / 31) |
| 56 | + } else { |
| 57 | + 7 + ((days - 186) / 30) |
| 58 | + }; |
| 59 | + |
| 60 | + result.day = if days < 186 { |
| 61 | + 1 + (days % 31) |
| 62 | + } else { |
| 63 | + 1 + ((days - 186) % 30) |
| 64 | + }; |
| 65 | + |
| 66 | + result |
| 67 | +} |
| 68 | + |
| 69 | +fn main() { |
| 70 | + let date = gregorian_to_jalali(2014, 2, 4); |
| 71 | + println!("{}", date); |
| 72 | +} |
| 73 | + |
| 74 | +#[cfg(test)] |
| 75 | +mod tests { |
| 76 | + use super::*; |
| 77 | + |
| 78 | + #[test] |
| 79 | + fn test_gregorian_to_jalali() { |
| 80 | + let date = gregorian_to_jalali(2025, 3, 20); |
| 81 | + assert_eq!(date.to_string(), "1403-12-30"); |
| 82 | + } |
| 83 | + |
| 84 | + #[test] |
| 85 | + fn test_gregorian_to_jalali_edge_case() { |
| 86 | + let date = gregorian_to_jalali(2025, 3, 21); |
| 87 | + assert_eq!(date.to_string(), "1404-01-01"); |
| 88 | + } |
| 89 | + |
| 90 | + #[test] |
| 91 | + fn test_display_format() { |
| 92 | + let date = gregorian_to_jalali(2014, 2, 4); |
| 93 | + assert_eq!(date.to_string(), "1392-11-15"); |
| 94 | + } |
| 95 | +} |
0 commit comments