1const MILLISECONDS_PER_DAY: i64 = 86_400_000;
4
5pub fn format_rfc3339(unix_ms: i64) -> String {
6 let days_since_epoch = unix_ms.div_euclid(MILLISECONDS_PER_DAY);
7 let millisecond_of_day = unix_ms.rem_euclid(MILLISECONDS_PER_DAY);
8 let (year, month, day) = civil_from_days(days_since_epoch);
9 let hours = millisecond_of_day / 3_600_000;
10 let minutes = millisecond_of_day / 60_000 % 60;
11 let seconds = millisecond_of_day / 1000 % 60;
12 let milliseconds = millisecond_of_day % 1000;
13 if milliseconds == 0 {
14 format!("{year:04}-{month:02}-{day:02}T{hours:02}:{minutes:02}:{seconds:02}Z")
15 } else {
16 format!(
17 "{year:04}-{month:02}-{day:02}T{hours:02}:{minutes:02}:{seconds:02}.{milliseconds:03}Z"
18 )
19 }
20}
21
22pub fn format_rfc5322(unix_ms: i64) -> String {
24 const WEEKDAY_NAMES: [&str; 7] = ["Thu", "Fri", "Sat", "Sun", "Mon", "Tue", "Wed"];
25 const MONTH_NAMES: [&str; 12] = [
26 "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
27 ];
28 let days_since_epoch = unix_ms.div_euclid(MILLISECONDS_PER_DAY);
29 let second_of_day = unix_ms.rem_euclid(MILLISECONDS_PER_DAY) / 1000;
30 let (year, month, day) = civil_from_days(days_since_epoch);
31 let weekday_name =
32 WEEKDAY_NAMES[usize::try_from(days_since_epoch.rem_euclid(7)).unwrap_or_default()];
33 let month_name = MONTH_NAMES[usize::try_from(month - 1).unwrap_or_default()];
34 format!(
35 "{weekday_name}, {day:02} {month_name} {year} {:02}:{:02}:{:02} +0000",
36 second_of_day / 3600,
37 second_of_day / 60 % 60,
38 second_of_day % 60
39 )
40}
41
42pub fn parse_rfc3339(timestamp_text: &str) -> Option<i64> {
44 let (date_text, time_text) = timestamp_text.trim().split_once(['T', 't', ' '])?;
45 let mut date_parts = date_text.split('-');
46 let year: i64 = date_parts.next()?.parse().ok()?;
47 let month: i64 = date_parts.next()?.parse().ok()?;
48 let day: i64 = date_parts.next()?.parse().ok()?;
49 let (clock_text, offset_ms) = split_offset(time_text)?;
50 let mut clock_parts = clock_text.split(':');
51 let hours: i64 = clock_parts.next()?.parse().ok()?;
52 let minutes: i64 = clock_parts.next()?.parse().ok()?;
53 let seconds_text = clock_parts.next().unwrap_or("0");
54 let (whole_seconds_text, fraction_text) =
55 seconds_text.split_once('.').unwrap_or((seconds_text, ""));
56 let seconds: i64 = whole_seconds_text.parse().ok()?;
57 let milliseconds: i64 = format!("{fraction_text:0<3}").get(..3)?.parse().ok()?;
58 let is_valid = (1..=12).contains(&month)
59 && (1..=31).contains(&day)
60 && hours < 24
61 && minutes < 60
62 && seconds < 61;
63 is_valid.then(|| {
64 days_from_civil(year, month, day) * MILLISECONDS_PER_DAY
65 + hours * 3_600_000
66 + minutes * 60_000
67 + seconds * 1000
68 + milliseconds
69 - offset_ms
70 })
71}
72
73pub fn parse_duration_ms(duration_text: &str) -> Option<u64> {
75 let duration_text = duration_text.trim();
76 let (number_text, unit_ms) = if let Some(number_text) = duration_text.strip_suffix("ms") {
77 (number_text, 1)
78 } else if let Some(number_text) = duration_text.strip_suffix('s') {
79 (number_text, 1000)
80 } else if let Some(number_text) = duration_text.strip_suffix('m') {
81 (number_text, 60_000)
82 } else {
83 (duration_text, 1000)
84 };
85 number_text
86 .trim()
87 .parse::<u64>()
88 .ok()
89 .map(|number| number * unit_ms)
90}
91
92fn split_offset(time_text: &str) -> Option<(&str, i64)> {
93 if let Some(clock_text) = time_text.strip_suffix(['Z', 'z']) {
94 return Some((clock_text, 0));
95 }
96 let sign_position = time_text.rfind(['+', '-'])?;
97 let (clock_text, offset_text) = time_text.split_at(sign_position);
98 let sign = if offset_text.starts_with('-') { -1 } else { 1 };
99 let (offset_hours, offset_minutes) = offset_text[1..].split_once(':')?;
100 let offset_ms =
101 (offset_hours.parse::<i64>().ok()? * 60 + offset_minutes.parse::<i64>().ok()?) * 60_000;
102 Some((clock_text, sign * offset_ms))
103}
104
105const DAY_MS: i64 = 86_400_000;
106
107pub fn add_calendar_months(unix_ms: i64, month_count: i64) -> i64 {
110 let days_since_epoch = unix_ms.div_euclid(DAY_MS);
111 let time_of_day_ms = unix_ms.rem_euclid(DAY_MS);
112 let (year, month, day) = civil_from_days(days_since_epoch);
113 let month_number = year * 12 + (month - 1) + month_count;
114 let (next_year, next_month) = (month_number.div_euclid(12), month_number.rem_euclid(12) + 1);
115 let next_month_start = days_from_civil(next_year, next_month, 1);
116 let following_month_start = days_from_civil(
117 (month_number + 1).div_euclid(12),
118 (month_number + 1).rem_euclid(12) + 1,
119 1,
120 );
121 let last_day = following_month_start - next_month_start;
122 let next_day = day.min(last_day);
123 (next_month_start + next_day - 1) * DAY_MS + time_of_day_ms
124}
125
126fn civil_from_days(days_since_epoch: i64) -> (i64, i64, i64) {
127 let shifted_days = days_since_epoch + 719_468;
128 let era = shifted_days.div_euclid(146_097);
129 let day_of_era = shifted_days.rem_euclid(146_097);
130 let year_of_era =
131 (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
132 let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
133 let month_index = (5 * day_of_year + 2) / 153;
134 let day = day_of_year - (153 * month_index + 2) / 5 + 1;
135 let month = if month_index < 10 {
136 month_index + 3
137 } else {
138 month_index - 9
139 };
140 let year = year_of_era + era * 400 + i64::from(month <= 2);
141 (year, month, day)
142}
143
144fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
145 let shifted_year = if month <= 2 { year - 1 } else { year };
146 let era = shifted_year.div_euclid(400);
147 let year_of_era = shifted_year.rem_euclid(400);
148 let month_index = if month > 2 { month - 3 } else { month + 9 };
149 let day_of_year = (153 * month_index + 2) / 5 + day - 1;
150 let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
151 era * 146_097 + day_of_era - 719_468
152}
153
154#[cfg(test)]
155mod tests {
156 use super::*;
157
158 #[test]
159 fn calendar_months_end_on_the_last_day_of_a_shorter_month() {
160 let january_31 = parse_rfc3339("2026-01-31T10:00:00Z").unwrap_or_default();
161 let december_15 = parse_rfc3339("2026-12-15T08:30:00Z").unwrap_or_default();
162
163 assert_eq!(
164 format_rfc3339(add_calendar_months(january_31, 1)),
165 "2026-02-28T10:00:00Z"
166 );
167 assert_eq!(
168 format_rfc3339(add_calendar_months(january_31, 12)),
169 "2027-01-31T10:00:00Z"
170 );
171 assert_eq!(
172 format_rfc3339(add_calendar_months(december_15, 1)),
173 "2027-01-15T08:30:00Z"
174 );
175 }
176
177 #[test]
179 fn formats_unix_milliseconds_as_rfc3339_utc() {
180 assert_eq!(format_rfc3339(0), "1970-01-01T00:00:00Z");
181 assert_eq!(format_rfc3339(1_767_225_600_000), "2026-01-01T00:00:00Z");
182 assert_eq!(
183 format_rfc3339(1_709_210_096_789),
184 "2024-02-29T12:34:56.789Z"
185 );
186 }
187
188 #[test]
189 fn reads_what_it_writes_and_offsets() {
190 for unix_ms in [0, 1_767_225_600_000, 1_709_210_096_789, 951_782_400_000] {
191 assert_eq!(parse_rfc3339(&format_rfc3339(unix_ms)), Some(unix_ms));
192 }
193 assert_eq!(
194 parse_rfc3339("2026-01-01T06:00:00+06:00"),
195 Some(1_767_225_600_000)
196 );
197 assert_eq!(parse_rfc3339("not a time"), None);
198 assert_eq!(parse_rfc3339("2026-13-01T00:00:00Z"), None);
199 }
200
201 #[test]
202 fn formats_the_date_header_form() {
203 assert_eq!(format_rfc5322(0), "Thu, 01 Jan 1970 00:00:00 +0000");
204 assert_eq!(
205 format_rfc5322(1_793_268_000_000),
206 "Thu, 29 Oct 2026 10:00:00 +0000"
207 );
208 }
209
210 #[test]
211 fn reads_durations() {
212 assert_eq!(parse_duration_ms("30s"), Some(30_000));
213 assert_eq!(parse_duration_ms("500ms"), Some(500));
214 assert_eq!(parse_duration_ms("2m"), Some(120_000));
215 assert_eq!(parse_duration_ms("5"), Some(5000));
216 assert_eq!(parse_duration_ms("soon"), None);
217 }
218}