Question to chrono and iterate over months

⚓ Rust    📅 2025-10-14    👤 surdeus    👁️ 3      

surdeus

I try to port an small Java Tool to rust and have some porting issues like that one.

I would like to iterate from local_minus_six_months month to local_now and create an arry/list similar to the java code below.

I was able to calculate the minus 7 month from now on but haven't seen any chrono function which allows to iterate from an startpoint to the destination similar to datesUntil. Is there something similar or do I need to solve this in another way?

Could be jiff a better aproach?

Rust:

use std::process::exit;
use chrono::{Local, Months};

fn main() {
    println!("Hello, world!");
    let local_now = Local::now();

    let local_minus_n_months = match local_now.checked_sub_months(Months::new(7)) {
        None => {
            println!("Error at checked_sub_months");
            exit(-1);
        },
        Some(new_months) => new_months,
    };
    println!("Now {}",local_now.format("%Y-%m"));
    println!("-6M {}",local_minus_n_months.format("%Y-%m"));
}

Java:
The code below creates a String toGlobFiles which holds the direcory glob in that format *{YYYY-MM,YYYY-MM,YYYY-MM}*.{gz,log}


        StringBuffer toGlobFiles = new StringBuffer("*{");
		LocalDate ldStart = LocalDate.now().minusMonths(6);

		// Calculate the Date range
		List<LocalDate> dates = ldStart // Determine your beginning `LocalDate` object.
				.datesUntil(            // Generate stream of `LocalDate` objects.
		           ldStart.plusMonths(7), 
                   Period.ofMonths(1) // Calculate your ending date, and ask for a stream of
																	// dates till then.
				) // Returns the stream.
				.collect(Collectors.toList()); // Collect your resulting dates in a `List`.

		for (LocalDate localDate : dates) {
			logger.info("{}", localDate.format(DateTimeFormatter.ofPattern("YYYY-MM,")));
			toGlobFiles.append(localDate.format(DateTimeFormatter.ofPattern("YYYY-MM,")));

       // Remove last ',' from the loop above
       toGlobFiles.setLength(toGlobFiles.length() - 1);
       toGlobFiles.append("}*.{gz,log}");

       logger.info("toGlobFiles {}", toGlobFiles);
		}

1 post - 1 participant

Read full topic

🏷️ Rust_feed