Skip to content

(core): Add Duration.minus method #16535

@moltar

Description

@moltar

There is already a Duration.plus method which allows to add two durations together.

However, there is no Duration.minus.

public plus(rhs: Duration): Duration {
const targetUnit = finestUnit(this.unit, rhs.unit);
const total = convert(this.amount, this.unit, targetUnit, {}) + convert(rhs.amount, rhs.unit, targetUnit, {});
return new Duration(total, targetUnit);
}

Use Case

Ability to subtract one duration from another.

For example, a CloudWatch trigger that executes a lambda every 5 minutes.

At the same time, I want to avoid race conditions, so I want to set the Lambda timeout to slightly less than 5 minutes.

Proposed Solution

const ruleSchedule = Duration.minutes(5)
const lambdaTimeout = ruleSchedule.minus(Duration.seconds(10))

Other

I tried creating a Duration with a negative value, to then do simple math, but that is not allowed.

throw new Error(`Duration amounts cannot be negative. Received: ${amount}`);

  • 👋 I may be able to implement this feature request
  • ⚠️ This feature might incur a breaking change

This is a 🚀 Feature Request

Metadata

Metadata

Assignees

No one assigned

    Labels

    @aws-cdk/coreRelated to core CDK functionalityeffort/smallSmall work item – less than a day of effortfeature-requestA feature should be added or improved.p2

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions