1use chrono::{Datelike, NaiveDate, NaiveDateTime, NaiveTime, Weekday};
4
5use crate::{Error, Result, Value};
6
7use super::clock::ClockKind;
8use super::construct::date_from_week;
9use super::duration::parse_duration_iso;
10use super::duration_pattern::parse_duration_pattern;
11use super::pattern::{invalid_value, parse_instant_pattern};
12use super::zone::{
13 parse_offset, resolve_wall_forward, sub_offset, zone_kind, zone_offset_mismatch, OverlapPolicy,
14 ZoneSpec,
15};
16use super::{range_err, weekday_from_i, Temporal};
17
18pub fn parse_iso(kind: &str, s: &str) -> Result<Temporal> {
19 match kind {
20 "date" => parse_date_str(s),
21 "localtime" => parse_naive_time(s).map(Temporal::LocalTime),
26 "time" => parse_time_str(s),
27 "localdatetime" => parse_localdatetime_str(s),
28 "datetime" => parse_zoned_dt(s),
29 "duration" => parse_duration_iso(s),
30 _ => Err(Error::ty(format!("unknown temporal kind {kind}"))),
31 }
32}
33
34fn time_has_offset(s: &str) -> bool {
38 s.contains('+') || s.contains('Z') || s.get(1..).unwrap_or("").contains('-')
39}
40
41fn parse_time_str(s: &str) -> Result<Temporal> {
46 if s.contains('[') {
47 return Err(Error::argument_error(
48 "Using a named time zone is not valid for a time without a date.",
49 ));
50 }
51 if time_has_offset(s) {
52 return parse_zoned_time(s);
53 }
54 parse_naive_time(s).map(|time| Temporal::Time { time, offset: 0 })
55}
56
57pub fn parse_pattern(kind: &str, value: &str, pattern: &str) -> Result<Temporal> {
58 if value.is_empty() || pattern.is_empty() {
59 return Err(invalid_value("empty temporal value or pattern"));
60 }
61 if kind == "duration" {
62 return parse_duration_pattern(value, pattern);
63 }
64 let kind = ClockKind::from_name(kind)
65 .ok_or_else(|| invalid_value(format!("unknown temporal kind {kind}")))?;
66 parse_instant_pattern(kind, value, pattern)
67}
68
69fn parse_civil_ymd(s: &str) -> Option<(i64, u32, u32)> {
70 let t = s.trim();
71 let (sign, rest) = if let Some(rest) = t.strip_prefix('+') {
72 (1i64, rest)
73 } else if let Some(rest) = t.strip_prefix('-') {
74 if rest.as_bytes().first().is_some_and(u8::is_ascii_digit) {
75 (-1i64, rest)
76 } else {
77 (1i64, t)
78 }
79 } else {
80 (1i64, t)
81 };
82 let mut parts = rest.split('-');
83 let year = parts.next()?.parse::<i64>().ok()? * sign;
84 let month = parts.next()?.parse().ok()?;
85 let day = parts.next()?.parse().ok()?;
86 Some((year, month, day))
87}
88
89fn parse_date_str(s: &str) -> Result<Temporal> {
90 if let Some((year, month, day)) = parse_civil_ymd(s) {
91 if (i64::from(NaiveDate::MIN.year())..=i64::from(NaiveDate::MAX.year())).contains(&year) {
96 let date =
97 NaiveDate::from_ymd_opt(i32::try_from(year).map_err(|_| range_err())?, month, day)
98 .ok_or_else(|| Error::ty(format!("invalid date '{s}'")))?;
99 return Ok(Temporal::Date(date));
100 }
101 if !is_civil_date(year, month, day) {
102 return Err(Error::ty(format!("invalid date '{s}'")));
103 }
104 return Ok(Temporal::CivilDate { year, month, day });
105 }
106 let t = s.trim().trim_start_matches('+');
107 parse_date_flexible(t)
108 .map(Temporal::Date)
109 .ok_or_else(|| Error::ty(format!("cannot parse date '{s}'")))
110}
111
112fn is_civil_date(year: i64, month: u32, day: u32) -> bool {
115 days_in_month(year, month).is_some_and(|length| (1..=length).contains(&day))
116}
117
118fn days_in_month(year: i64, month: u32) -> Option<u32> {
123 Some(match month {
124 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
125 4 | 6 | 9 | 11 => 30,
126 2 if year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) => 29,
127 2 => 28,
128 _ => return None,
129 })
130}
131
132pub fn padded_iso_date_value(s: &str) -> Option<Value> {
141 let b = s.as_bytes();
142 if b.len() != 10 || b[4] != b'-' || b[7] != b'-' {
143 return None;
144 }
145 let digits = |slot: &[u8]| slot.iter().all(u8::is_ascii_digit);
146 if !(digits(&b[..4]) && digits(&b[5..7]) && digits(&b[8..])) {
147 return None;
148 }
149 let year: i32 = s[..4].parse().ok()?;
150 let month: u32 = s[5..7].parse().ok()?;
151 let day: u32 = s[8..].parse().ok()?;
152 NaiveDate::from_ymd_opt(year, month, day).map(|d| Value::Temporal(Temporal::Date(d)))
153}
154
155fn parse_date_flexible(s: &str) -> Option<NaiveDate> {
156 let t = s.trim().trim_start_matches('+');
157 if let Ok(d) = NaiveDate::parse_from_str(t, "%Y-%m-%d") {
158 return Some(d);
159 }
160 if let Ok(d) = NaiveDate::parse_from_str(t, "%Y%m%d") {
161 return Some(d);
162 }
163 if t.len() == 7 && t.as_bytes().get(4) == Some(&b'-') {
164 if let (Ok(y), Ok(m)) = (t[..4].parse::<i32>(), t[5..].parse::<u32>()) {
165 return NaiveDate::from_ymd_opt(y, m, 1);
166 }
167 }
168 if t.len() == 6 && t.chars().all(|c| c.is_ascii_digit()) {
169 if let Ok(d) = NaiveDate::parse_from_str(&format!("{t}01"), "%Y%m%d") {
170 return Some(d);
171 }
172 }
173 if t.len() == 4 && t.chars().all(|c| c.is_ascii_digit()) {
174 return NaiveDate::from_ymd_opt(t.parse().ok()?, 1, 1);
175 }
176 if let Some(d) = parse_week_date(t) {
177 return Some(d);
178 }
179 parse_ordinal_date(t)
180}
181
182fn parse_week_date(s: &str) -> Option<NaiveDate> {
183 let compact = s.contains('W') && !s.contains('-');
184 let rest = s.split_once('W')?.1;
185 let year: i32 = s.split(['W', '-']).next()?.parse().ok()?;
186 if compact {
187 if rest.len() >= 3 {
188 let week: u32 = rest.get(..2)?.parse().ok()?;
189 let dow = rest.get(2..)?.parse::<u32>().unwrap_or(1);
190 return date_from_week(year, week, weekday_from_i(i64::from(dow))).ok();
191 }
192 let week: u32 = rest.parse().ok()?;
193 return date_from_week(year, week, Weekday::Mon).ok();
194 }
195 let parts: Vec<&str> = rest.split('-').collect();
196 let week: u32 = parts.first()?.parse().ok()?;
197 let dow = parts
198 .get(1)
199 .and_then(|p| p.parse::<i64>().ok())
200 .unwrap_or(1);
201 date_from_week(year, week, weekday_from_i(dow)).ok()
202}
203
204fn parse_ordinal_date(s: &str) -> Option<NaiveDate> {
205 if let Some((y, d)) = s.split_once('-') {
206 if y.len() == 4 && d.len() == 3 && d.chars().all(|c| c.is_ascii_digit()) {
207 return NaiveDate::from_yo_opt(y.parse().ok()?, d.parse().ok()?);
208 }
209 }
210 if s.len() == 7 && s.chars().all(|c| c.is_ascii_digit()) {
211 return NaiveDate::from_yo_opt(s[..4].parse().ok()?, s[4..].parse().ok()?);
212 }
213 None
214}
215
216fn parse_localdatetime_str(s: &str) -> Result<Temporal> {
217 let (body, _) = split_offset(s);
218 if let Ok(dt) = parse_naive_dt(body) {
219 return Ok(Temporal::LocalDateTime(dt));
220 }
221 let (date_s, time_s) = match body.split_once('T') {
222 Some((d, t)) => (d, Some(t)),
223 None => (body, None),
224 };
225 if let Temporal::CivilDate { year, month, day } = parse_date_str(date_s)? {
226 let time = match time_s {
227 Some(t) if !t.is_empty() => parse_naive_time(t).unwrap_or(NaiveTime::MIN),
228 _ => NaiveTime::MIN,
229 };
230 return Ok(Temporal::CivilDateTime {
231 year,
232 month,
233 day,
234 time,
235 });
236 }
237 Err(Error::ty(format!("cannot parse localdatetime '{s}'")))
238}
239
240fn parse_naive_time(s: &str) -> Result<NaiveTime> {
241 for fmt in ["%H:%M:%S%.f", "%H:%M:%S", "%H:%M", "%H%M%S", "%H%M"] {
242 if let Ok(t) = NaiveTime::parse_from_str(s, fmt) {
243 return Ok(t);
244 }
245 }
246 if let Some((hms, frac)) = s.split_once('.') {
247 if hms.len() == 6 && hms.chars().all(|c| c.is_ascii_digit()) {
248 let h: u32 = hms[..2].parse().unwrap_or(0);
249 let m: u32 = hms[2..4].parse().unwrap_or(0);
250 let sec: u32 = hms[4..].parse().unwrap_or(0);
251 let mut nano = 0u32;
252 let mut place = 100_000_000u32;
253 for c in frac.chars().filter(|c| c.is_ascii_digit()) {
254 nano += (c as u32 - b'0' as u32) * place;
255 place /= 10;
256 if place == 0 {
257 break;
258 }
259 }
260 if let Some(t) = NaiveTime::from_hms_nano_opt(h, m, sec, nano) {
261 return Ok(t);
262 }
263 }
264 }
265 if s.chars().all(|c| c.is_ascii_digit()) {
266 let padded = match s.len() {
267 1 | 2 => format!("{s:0>2}0000"),
268 4 => format!("{s}00"),
269 6 => s.to_string(),
270 _ => String::new(),
271 };
272 if padded.len() == 6 {
273 if let Ok(t) = NaiveTime::parse_from_str(&padded, "%H%M%S") {
274 return Ok(t);
275 }
276 }
277 }
278 Err(Error::ty(format!("cannot parse time '{s}'")))
279}
280
281pub fn datetime_from_epoch(seconds: i64, nanos: i64) -> Result<Temporal> {
282 let utc = chrono::DateTime::from_timestamp(seconds, nanos.clamp(0, 999_999_999) as u32)
283 .ok_or_else(|| Error::ty("epoch out of range"))?
284 .naive_utc();
285 Ok(Temporal::DateTime {
286 utc,
287 offset: 0,
288 zone: Some("Z".into()),
289 })
290}
291
292pub fn datetime_from_epoch_millis(ms: i64) -> Result<Temporal> {
293 datetime_from_epoch(ms.div_euclid(1000), (ms.rem_euclid(1000)) * 1_000_000)
294}
295
296fn parse_naive_dt(s: &str) -> Result<NaiveDateTime> {
297 let (body, _) = split_offset(s);
300 let unsigned = body.trim_start_matches('+');
306 for candidate in [body, unsigned] {
307 for fmt in [
308 "%Y-%m-%dT%H:%M:%S%.f",
309 "%Y-%m-%dT%H:%M:%S",
310 "%Y-%m-%dT%H:%M",
311 "%Y-%m-%dT%H",
312 ] {
313 if let Ok(dt) = NaiveDateTime::parse_from_str(candidate, fmt) {
314 return Ok(dt);
315 }
316 }
317 if let Ok(d) = NaiveDate::parse_from_str(candidate, "%Y-%m-%d") {
318 return Ok(d.and_time(NaiveTime::MIN));
319 }
320 }
321 let (date_s, time_s) = unsigned.split_once('T').unwrap_or((unsigned, ""));
323 let date = parse_date_flexible(date_s)
324 .ok_or_else(|| Error::ty(format!("cannot parse localdatetime '{s}'")))?;
325 let time = if time_s.is_empty() {
326 NaiveTime::MIN
327 } else {
328 parse_naive_time(time_s)?
329 };
330 Ok(date.and_time(time))
331}
332
333fn split_offset(s: &str) -> (&str, Option<&str>) {
334 if let Some(i) = s.find('Z') {
335 return (&s[..i], Some("Z"));
336 }
337 if let Some(i) = s.rfind('+') {
338 if i > 0 {
339 return (&s[..i], Some(&s[i..]));
340 }
341 }
342 if let Some(i) = s.rfind('-') {
343 if i > 0 && s.as_bytes()[i - 1].is_ascii_digit() {
344 if s[..i].contains('T') || s[..i].contains(':') {
345 return (&s[..i], Some(&s[i..]));
346 }
347 let body = &s[..i];
348 let off = &s[i + 1..];
349 let compact_time = body.chars().all(|c| c.is_ascii_digit() || c == '.');
350 let offset_ok = off.contains(':')
351 && off.chars().all(|c| c.is_ascii_digit() || c == ':')
352 || off.chars().all(|c| c.is_ascii_digit()) && matches!(off.len(), 2 | 4);
353 if compact_time && offset_ok {
354 return (&s[..i], Some(&s[i..]));
355 }
356 }
357 }
358 (s, None)
359}
360
361fn parse_zoned_time(s: &str) -> Result<Temporal> {
365 let (body, off) = split_offset(s);
366 let time = parse_naive_time(body)?;
367 let offset = off.map(parse_offset).transpose()?.unwrap_or(0);
368 Ok(Temporal::Time { time, offset })
369}
370
371fn check_matching_offset(zone: &str, want: Option<i32>, actual: i32) -> Result<()> {
376 if want.is_some_and(|want| want != actual) {
377 return Err(zone_offset_mismatch(zone));
378 }
379 Ok(())
380}
381
382fn parse_zoned_dt(s: &str) -> Result<Temporal> {
383 let (body, zone_part) = if let Some(i) = s.find('[') {
384 (&s[..i], Some(s[i + 1..].trim_end_matches(']')))
385 } else {
386 let (b, o) = split_offset(s);
387 (b, o)
388 };
389 let (body, body_offset) = split_offset(body);
393 let local = parse_naive_dt(body)?;
394 if let Some(z) = zone_part {
395 let want = body_offset.map(parse_offset).transpose()?;
396 let spec = zone_kind(z);
400 let (local, offset, zone) = match spec {
401 ZoneSpec::Iana(_) | ZoneSpec::Other(_) => {
402 let policy = want.map_or(OverlapPolicy::Reject, OverlapPolicy::Require);
406 let (local, offset) = resolve_wall_forward(z, local, policy)?;
407 (local, offset, Some(z.to_string()))
408 }
409 ZoneSpec::Utc => {
410 check_matching_offset(z, want, 0)?;
411 (local, 0, Some("Z".into()))
412 }
413 ZoneSpec::Fixed(_) | ZoneSpec::Prefixed(_) => {
417 let offset = parse_offset(z)?;
418 check_matching_offset(z, want, offset)?;
419 let zone = matches!(spec, ZoneSpec::Prefixed(_)).then(|| z.to_string());
420 (local, offset, zone)
421 }
422 };
423 return Ok(Temporal::DateTime {
424 utc: sub_offset(local, offset)?,
425 offset,
426 zone,
427 });
428 }
429 Ok(Temporal::DateTime {
430 utc: local,
431 offset: 0,
432 zone: Some("Z".into()),
433 })
434}