Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 15 additions & 14 deletions lib/shared/dateHelper.js
Original file line number Diff line number Diff line change
@@ -1,28 +1,29 @@
import { Duration, ZonedDateTime } from '@js-joda/core'
import { toTime } from '@secvisogram/is-leap-second'

/**
* compare ZonedDateTimes from js-joda
* returns a negative number if a is less than b, positive if a is greater than b, and zero if they are equal.
* This function also returns 0 if one of the given values could not be parsed.
*
* @param {ZonedDateTime | string} a
* @param {ZonedDateTime | string} b
* @returns {0|1|-1}
* Compares two date-time strings using `toTime` from `@secvisogram/is-leap-second`.
* Returns a negative number if `a` is less than `b`, a positive number if `a` is greater
* than `b`, and zero if they are equal. Also returns 0 if either value cannot be parsed.
* Follows the comparator convention used by `Array.prototype.sort`.
*
* @param {string} a - The first date-time string to compare.
* @param {string} b - The second date-time string to compare.
* @returns {0|1|-1} Negative if `a < b`, positive if `a > b`, zero if equal or unparseable.
*/
export const compareZonedDateTimes = (a, b) => {
// catch js-joda exception if a or b can't be parsed
// catch TypeError exception if a or b can't be parsed
try {
const date1 = a instanceof ZonedDateTime ? a : ZonedDateTime.parse(a)
const date2 = b instanceof ZonedDateTime ? b : ZonedDateTime.parse(b)
const duration = Duration.between(date1, date2)
const date1 = toTime(a)
const date2 = toTime(b)
if (date1 === null || date2 === null) return 0
const duration = date2 - date1

// return number based on js sort function
// > negative if a is less than b, positive if a is greater than b, and zero if they are equal.
// [Sort Documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#comparefn)
if (duration.isZero()) {
if (duration === 0n) {
return 0
} else if (duration.isNegative()) {
} else if (duration < 0n) {
return 1
} else {
return -1
Expand Down
7 changes: 7 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@
"dependencies": {
"@js-joda/core": "^5.6.1",
"@js-joda/timezone": "^2.18.2",
"@secvisogram/is-leap-second": "^0.1.0",
"ajv": "^8.11.2",
"ajv-formats": "^3.0.1",
"bcp47": "^1.1.2",
Expand Down
Loading