Skip to content

Operations on NaiveDate are not commutative. #1345

Closed
@dcechano

Description

@dcechano

When taking an arbitrary date, 2022-05-15 for example, and performing operations on that date, the order of operations does appear to matter.

For example, taking the date above and subtracting 20 years, then adding 111 months, then 1000 days is not the same as taking the same date, adding 1000 days, subtracting 20 years and adding 111 months. I have pasted some code below that shows this:

        let expected = NaiveDate::parse_from_str("2014-05-11","%Y-%m-%d").unwrap();

        let mut date = NaiveDate::parse_from_str("2022-05-15", "%Y-%m-%d").unwrap();
        date = date.sub(Months::new(20 * 12)).add(Months::new(111)).add(Duration::days(1000));
        assert_eq!(expected, date);


        let mut date = NaiveDate::parse_from_str("2022-05-15", "%Y-%m-%d").unwrap();
        date = date.add(Duration::days(1000)).sub(Months::new(20 * 12)).add(Months::new(111));
        assert_eq!(expected, date);

The 2nd assertion fails with the date variable showing 2014-05-08, which is 3 days off from the expected 2014-05-11.

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