Skip to content

Add a function for getting the number of days in the current month #1661

@aslilac

Description

@aslilac

Recently I wrote some code for picking recurring dates. If it's supposed to recur monthly on a day that is acceptable in some months (January 31st) but not in others (January 31st) then it instead will happen on the last day of the month.

Currently I'm resorting to the following:

fn with_day_saturated<Tz: chrono::TimeZone>(datetime: DateTime<Tz>, day: u32) -> DateTime<Tz> {
	let day = day.clamp(1, 31);
	if datetime.day() == day {
		return datetime;
	}

	// We check back up to 3 days, because non-leap year February is the worst
	// case scenario. 31 - 3 = 28, which guarantees that we end up in bounds.
	datetime
		.with_day(day)
		.or_else(|| datetime.with_day(day - 1))
		.or_else(|| datetime.with_day(day - 2))
		.or_else(|| datetime.with_day(day - 3))
		.unwrap()
}

...which is obviously not ideal. 😅

It'd be great if there was some better way to figure out what the last day of the current month was. I could use that in the .clamp instead and delete half of this code.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions