Skip to content

Commit

Permalink
Support converting large dates (i.e. +10999-12-31) from string to Date32
Browse files Browse the repository at this point in the history
  • Loading branch information
phillipleblanc committed Feb 4, 2025
1 parent 9327f47 commit 93934bf
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
17 changes: 17 additions & 0 deletions arrow-cast/src/cast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4339,6 +4339,23 @@ mod tests {
}
}

#[test]
fn test_cast_string_with_large_date_to_date32() {
let array = Arc::new(StringArray::from(vec![
Some("+10999-12-31"),
Some("-0010-02-28")
])) as ArrayRef;
let to_type = DataType::Date32;
let options = CastOptions {
safe: false,
format_options: FormatOptions::default(),
};
let b = cast_with_options(&array, &to_type, &options).unwrap();
let c = b.as_primitive::<Date32Type>();
assert_eq!(3298139, c.value(0));
assert_eq!(-723122, c.value(1));
}

#[test]
fn test_cast_string_format_yyyymmdd_to_date32() {
let a0 = Arc::new(StringViewArray::from(vec![
Expand Down
20 changes: 20 additions & 0 deletions arrow-cast/src/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -595,6 +595,26 @@ const EPOCH_DAYS_FROM_CE: i32 = 719_163;
const ERR_NANOSECONDS_NOT_SUPPORTED: &str = "The dates that can be represented as nanoseconds have to be between 1677-09-21T00:12:44.0 and 2262-04-11T23:47:16.854775804";

fn parse_date(string: &str) -> Option<NaiveDate> {
// If the date has an extended (signed) year such as "+10999-12-31" or "-0012-05-06"
if string.starts_with('+') || string.starts_with('-') {
// Skip the sign and look for the hyphen that terminates the year digits.
// According to ISO 8601 the unsigned part must be at least 4 digits.
let rest = &string[1..];
let hyphen = rest.find('-')?;
if hyphen < 4 {
return None;
}
// The year substring is the sign and the digits (but not the separator)
// e.g. for "+10999-12-31", hyphen is 5 and s[..6] is "+10999"
let year: i32 = string[..hyphen + 1].parse().ok()?;
// The remainder should begin with a '-' which we strip off, leaving the month-day part.
let remainder = string[hyphen + 1..].strip_prefix('-')?;
let mut parts = remainder.splitn(2, '-');
let month: u32 = parts.next()?.parse().ok()?;
let day: u32 = parts.next()?.parse().ok()?;
return NaiveDate::from_ymd_opt(year, month, day);
}

if string.len() > 10 {
// Try to parse as datetime and return just the date part
return string_to_datetime(&Utc, string)
Expand Down

0 comments on commit 93934bf

Please sign in to comment.