chronia
    Preparing search index...

    Function compare

    • Compare two Date objects or timestamps chronologically with configurable sort order.

      Parameters

      • date1: number | Date

        The first Date object or timestamp to compare

      • date2: number | Date

        The second Date object or timestamp to compare

      • options: CompareOptions = ...

        Comparison options with default { order: "ASC" }

      Returns number

      -1 if date1 < date2, 1 if date1 > date2, 0 if equal (adjusted for order) Returns NaN if inputs are invalid

      // Compare Date objects with default ascending order
      compare(new Date('2024-01-01'), new Date('2024-01-02')); // -1 (ascending)
      compare(new Date('2024-01-01'), new Date('2024-01-01')); // 0 (equal)
      // Compare with explicit descending order
      compare(new Date('2024-01-01'), new Date('2024-01-02'), { order: 'DESC' }); // 1 (descending)
      // Compare timestamps
      const timestamp1 = new Date('2024-01-01').getTime();
      const timestamp2 = new Date('2024-01-02').getTime();
      compare(timestamp1, timestamp2); // -1 (ascending)
      compare(timestamp1, timestamp2, { order: 'DESC' }); // 1 (descending)
      // Compare mixed Date and timestamp inputs
      compare(new Date('2024-01-01'), new Date('2024-01-02').getTime()); // -1
      compare(timestamp1, new Date('2024-01-02')); // -1
      // Sort dates in ascending order (default)
      dates.sort(compare);
      // Sort dates in descending order
      dates.sort((a, b) => compare(a, b, { order: 'DESC' }));
      // Empty options object defaults to ascending order
      compare(date1, date2, {}); // Same as compare(date1, date2)
      // Order property is case-insensitive at runtime
      // These work at runtime even though TypeScript will show type errors:
      // compare(date1, date2, { order: 'desc' }); // treated as 'DESC'
      // compare(date1, date2, { order: 'asc' }); // treated as 'ASC'
      // compare(date1, date2, { order: 'xyz' }); // treated as 'ASC' (default)