Understanding `formatDistanceStrict` in date-fns: Strict Time Difference Formatting


Purpose

  • formatDistanceStrict is a function used to format the difference between two dates in a human-readable way, ensuring strict adherence to predefined units and thresholds.

Functionality

    • It takes two dates (date and baseDate) as arguments.
    • It calculates the time difference in milliseconds between the two dates.
  1. Determines the Unit

    • Based on the absolute value of the time difference, it selects the appropriate unit (seconds, minutes, hours, days, months, or years) for the formatted output.
  2. Applies Thresholds

    • formatDistanceStrict differs from other formatting functions in date-fns by using strict thresholds to determine the unit.
    • These thresholds ensure consistency in the output, even for small differences within a unit. For example, 59 seconds will always be formatted as "59 seconds" instead of rounding down to "less than a minute."
  3. Formats the Output

    • It formats the time difference using the chosen unit and its corresponding pluralization rules.
    • You can optionally customize the formatting using options like addSuffix (to include "ago" or "from now") and includeSeconds.

Example

import { formatDistanceStrict } from 'date-fns';

const now = new Date();
const oneMinuteAgo = new Date(now.getTime() - (60 * 1000));

const formattedDifference = formatDistanceStrict(oneMinuteAgo, now);
console.log(formattedDifference); // Output: 1 minute

Key Points

  • It's well-suited for scenarios where you need precise control over the displayed unit and threshold behavior.
  • formatDistanceStrict provides a more predictable and consistent way to format time differences compared to functions that might round down to smaller units for near-threshold cases.

Additional Considerations

  • For internationalization, explore the locale option provided by date-fns to adjust formatting based on different locales.
  • If you prefer more flexible formatting with potential rounding, consider using other formatting functions from date-fns like formatDistance or formatDuration.


Formatting Different Units

import { formatDistanceStrict } from 'date-fns';

const now = new Date();
const oneHourAgo = new Date(now.getTime() - (60 * 60 * 1000));
const oneDayAgo = new Date(now.getTime() - (24 * 60 * 60 * 1000));
const oneMonthAgo = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate());

console.log(formatDistanceStrict(oneHourAgo, now));   // Output: 1 hour
console.log(formatDistanceStrict(oneDayAgo, now));    // Output: 1 day
console.log(formatDistanceStrict(oneMonthAgo, now));  // Output: 1 month

Including Suffix ("ago" or "from now")

import { formatDistanceStrict } from 'date-fns';

const now = new Date();
const oneMinuteAgo = new Date(now.getTime() - (60 * 1000));

console.log(formatDistanceStrict(oneMinuteAgo, now, { addSuffix: true }));  // Output: 1 minute ago
console.log(formatDistanceStrict(now.getTime() + (10 * 60 * 1000), now, { addSuffix: true }));  // Output: 10 minutes from now
import { formatDistanceStrict } from 'date-fns';

const now = new Date();
const fiftyNineSecondsAgo = new Date(now.getTime() - (59 * 1000));
const sixtyOneSecondsAgo = new Date(now.getTime() - (61 * 1000));

console.log(formatDistanceStrict(fiftyNineSecondsAgo, now));  // Output: 59 seconds
console.log(formatDistanceStrict(sixtyOneSecondsAgo, now));   // Output: 1 minute


formatDistance (date-fns)

  • Example:
  • Might round down for differences very close to the next unit.
  • Uses "helper" words like "almost", "over", "less than" for near-threshold cases.
  • More flexible formatting approach.
import { formatDistance } from 'date-fns';

const now = new Date();
const oneMinuteAgo = new Date(now.getTime() - (60 * 1000));

const formattedDifference = formatDistance(oneMinuteAgo, now);
console.log(formattedDifference); // Output: "almost 1 minute ago" (may vary)

formatDuration (date-fns)

  • Example:
  • Useful if you need detailed time breakdowns (e.g., "2 hours, 3 minutes, 10 seconds").
  • Suitable for formatting the duration between two dates in a more precise way, including seconds.
import { formatDuration } from 'date-fns';

const now = new Date();
const twoHoursTenMinutesAgo = new Date(now.getTime() - (2 * 60 * 60 * 1000) - (10 * 60 * 1000));

const formattedDuration = formatDuration(twoHoursTenMinutesAgo, now);
console.log(formattedDuration); // Output: "2 hours, 10 minutes"

Custom Formatting Function

  • Example (basic implementation):
  • Requires more development effort but provides maximum flexibility.
  • This allows you to define custom logic for unit selection, thresholds, and output formatting.
  • For complete control over the formatting, you can create your own function.
function customFormatDistance(date, baseDate) {
  const diffInMs = Math.abs(date.getTime() - baseDate.getTime());
  const seconds = Math.floor(diffInMs / 1000);
  const minutes = Math.floor(seconds / 60);

  if (minutes < 1) {
    return `${seconds} seconds`;
  } else {
    return `${minutes} minutes`;
  }
}

const now = new Date();
const oneMinuteAgo = new Date(now.getTime() - (60 * 1000));

const formattedDifference = customFormatDistance(oneMinuteAgo, now);
console.log(formattedDifference); // Output: 1 minute
  • For maximum control, create a custom formatting function.
  • If detailed duration breakdown is needed, consider formatDuration.
  • If you prefer more natural language and flexibility with potential rounding, use formatDistance.
  • If you need strict unit adherence and predictable formatting, stick with formatDistanceStrict.