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 normalized = s.replace(' ', "T");
298 let (body, _) = split_offset(&normalized);
299 let unsigned = body.trim_start_matches('+');
305 for candidate in [body, unsigned] {
306 for fmt in [
307 "%Y-%m-%dT%H:%M:%S%.f",
308 "%Y-%m-%dT%H:%M:%S",
309 "%Y-%m-%dT%H:%M",
310 "%Y-%m-%dT%H",
311 "%Y-%m-%d",
312 ] {
313 if let Ok(dt) = NaiveDateTime::parse_from_str(candidate, fmt) {
314 return Ok(dt);
315 }
316 if fmt == "%Y-%m-%d" {
317 if let Ok(d) = NaiveDate::parse_from_str(candidate, fmt) {
318 return Ok(d.and_time(NaiveTime::MIN));
319 }
320 }
321 }
322 }
323 let (date_s, time_s) = match unsigned.split_once('T') {
324 Some((d, t)) => (d, t),
325 None => {
326 return parse_date_flexible(unsigned)
327 .map(|d| d.and_time(NaiveTime::MIN))
328 .ok_or_else(|| Error::ty(format!("cannot parse localdatetime '{s}'")));
329 }
330 };
331 let date = parse_date_flexible(date_s)
332 .ok_or_else(|| Error::ty(format!("cannot parse localdatetime '{s}'")))?;
333 let time = if time_s.is_empty() {
334 NaiveTime::MIN
335 } else {
336 parse_naive_time(time_s)?
337 };
338 Ok(date.and_time(time))
339}
340
341fn split_offset(s: &str) -> (&str, Option<&str>) {
342 if let Some(i) = s.find('Z') {
343 return (&s[..i], Some("Z"));
344 }
345 if let Some(i) = s.rfind('+') {
346 if i > 0 {
347 return (&s[..i], Some(&s[i..]));
348 }
349 }
350 if let Some(i) = s.rfind('-') {
351 if i > 0 && s.as_bytes()[i - 1].is_ascii_digit() {
352 if s[..i].contains('T') || s[..i].contains(':') {
353 return (&s[..i], Some(&s[i..]));
354 }
355 let body = &s[..i];
356 let off = &s[i + 1..];
357 let compact_time = body.chars().all(|c| c.is_ascii_digit() || c == '.');
358 let offset_ok = off.contains(':')
359 && off.chars().all(|c| c.is_ascii_digit() || c == ':')
360 || off.chars().all(|c| c.is_ascii_digit()) && matches!(off.len(), 2 | 4);
361 if compact_time && offset_ok {
362 return (&s[..i], Some(&s[i..]));
363 }
364 }
365 }
366 (s, None)
367}
368
369fn parse_zoned_time(s: &str) -> Result<Temporal> {
373 let (body, off) = split_offset(s);
374 let time = parse_naive_time(body)?;
375 let offset = off.map(parse_offset).transpose()?.unwrap_or(0);
376 Ok(Temporal::Time { time, offset })
377}
378
379fn check_matching_offset(zone: &str, want: Option<i32>, actual: i32) -> Result<()> {
384 if want.is_some_and(|want| want != actual) {
385 return Err(zone_offset_mismatch(zone));
386 }
387 Ok(())
388}
389
390fn parse_zoned_dt(s: &str) -> Result<Temporal> {
391 let (body, zone_part) = if let Some(i) = s.find('[') {
392 (&s[..i], Some(s[i + 1..].trim_end_matches(']')))
393 } else {
394 let (b, o) = split_offset(s);
395 (b, o)
396 };
397 let (body, body_offset) = split_offset(body);
401 let local = parse_naive_dt(body)?;
402 if let Some(z) = zone_part {
403 let want = body_offset.map(parse_offset).transpose()?;
404 let (local, offset, zone) = match zone_kind(z) {
408 ZoneSpec::Iana(_) | ZoneSpec::Other(_) => {
409 let policy = want.map_or(OverlapPolicy::Reject, OverlapPolicy::Require);
413 let (local, offset) = resolve_wall_forward(z, local, policy)?;
414 (local, offset, Some(z.to_string()))
415 }
416 ZoneSpec::Utc => {
417 check_matching_offset(z, want, 0)?;
418 (local, 0, Some("Z".into()))
419 }
420 ZoneSpec::Fixed(_) => {
424 let offset = parse_offset(z)?;
425 check_matching_offset(z, want, offset)?;
426 (local, offset, None)
427 }
428 ZoneSpec::Prefixed(_) => {
429 let offset = parse_offset(z)?;
430 check_matching_offset(z, want, offset)?;
431 (local, offset, Some(z.to_string()))
432 }
433 };
434 return Ok(Temporal::DateTime {
435 utc: sub_offset(local, offset)?,
436 offset,
437 zone,
438 });
439 }
440 Ok(Temporal::DateTime {
441 utc: local,
442 offset: 0,
443 zone: Some("Z".into()),
444 })
445}