Rusqlite + Chrono: How do I simplify code to obtain chrono datetime value

⚓ Rust    📅 2026-04-22    👤 surdeus    👁️ 2      

surdeus

I am working on a function that determines the latest date in an sqlite database then subtracts days from that date, returning a vector of 4 dates as strings in 2022-04-20 format. In the database the dates are of type text. Instead of creating the variable latest_date is there a way to directly use the results of the sql query in NaiveDate parse_from_str which would hopefully simplify the code. Any assistance will be appreciated.

pub fn get_start_dates() -> Vec<String> {

    let db_file_path: &str = "stock_data.db";
    let conn = match Connection::open(db_file_path) {
        Ok(con) => {
            con
        },
        Err(e) => {
            println!("Error creating connectiont to db: {}", e);
            return Vec::new()
        },
    };

    let latest_date: String = match conn.query_row("SELECT MAX(date) FROM data", [], |row| row.get(0)) {
        Ok(result)=> {
            result
        },
        Err(e) => {
            println!("Error getting latest date from db: {}", e);
            return Vec::new()
        },
    };

    let latest_datetime: NaiveDate = match NaiveDate::parse_from_str(&latest_date, "%Y-%m-%d") {
        Ok(result) => {
            result
        },
        Err(e) => {
            println!("Error parsing string date to datetime: {}", e);
            return Vec::new()
        },
    };

    let mut start_dates: Vec<String> = Vec::new();

    for num_days in [90, 180, 365, 3650] {
        let temp_value: String = match latest_datetime.checked_sub_days(Days::new(num_days)) {
            Some(result) => {
                result.format("%Y-%m-%d").to_string()
            },
            None => {
                println!("error");
                return Vec::new()
            },
        };
        start_dates.push(temp_value);        
    }
    start_dates
}

3 posts - 3 participants

Read full topic

🏷️ Rust_feed