Skip to content

Commit

Permalink
front: introduce Duration type
Browse files Browse the repository at this point in the history
Signed-off-by: Simon Ser <[email protected]>
References: #8816
  • Loading branch information
emersion committed Jan 10, 2025
1 parent 4aeb5fd commit 6f5a0ae
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions front/src/utils/duration.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/* eslint-disable import/prefer-default-export */

import dayjs from 'dayjs';

export class Duration {
/** Number of milliseconds */
readonly ms: number;

constructor(ms: number) {
this.ms = ms;
}

static zero = new Duration(0);

/** Parse an ISO 8601 duration string. */
static parse(str: string) {
return new Duration(dayjs.duration(str).asMilliseconds());
}

/** Subtract two dates. */
static subtractDate(a: Date, b: Date) {
return new Duration(a.getTime() - b.getTime());
}

// Return the number of milliseconds, so that comparison operators work as expected.
valueOf() {
return this.ms;
}

/** Format this duration as an ISO 8601 string. */
toString() {
return dayjs.duration(this.ms).toISOString();
}

toJSON() {
return this.toString();
}
}

0 comments on commit 6f5a0ae

Please sign in to comment.