Repository navigation
Counting Days In Span Without Weekends #663
|
Here's my attempt: let current_date = Zoned::now().date();
let end_date: Date = (irrelevant invoice period math);
let days_left = current_date.series(end_date - current_date).into_iter().filter(|d| d.weekday() != Weekday::Saturday && d.weekday() != Weekday::Sunday).count();My intention is to count all business days between two dates, inclusive. The true answer is always less than one month, but I'm getting values in the thousands. I find that pretty strange given that the iterator is iterating over individual dates. Previously I was directly making a span and then using Any advice would be appreciated! |
Replies: 1 comment 1 reply
|
It's because use jiff::{
civil::{Date, Weekday},
ToSpan, Zoned,
};
fn main() -> anyhow::Result<()> {
let current_date = Zoned::now().date();
let end_date: Date = current_date + 2.weeks();
let days_left = current_date
.series(1.day())
.take_while(|d| d <= &end_date)
.filter(|d| {
d.weekday() != Weekday::Saturday && d.weekday() != Weekday::Sunday
})
.count();
println!("{days_left}");
Ok(())
} |
It's because
end_date - current_dateproduces aSpanrepresenting the number of days between the dates, andDate::seriesaccepts an increment amount. So if the difference between two days is 14 days, thenserieswill return dates spaced 14 days apart. What you want instead is to count by single days and take elements while they are less than theend_date. Putting it all together, you get this: