Skip to content

⬅️ Back to Table of Contents

πŸ“„ useTimeAgo

πŸ“Š Analysis Summary

Metric Count
πŸ”§ Functions 15
πŸ“¦ Imports 9
πŸ“Š Variables & Constants 2
🟒 Vue Composition API 1
πŸ“ Interfaces 4
πŸ“‘ Type Aliases 4

πŸ“š Table of Contents

πŸ› οΈ File Location:

πŸ“‚ packages/core/useTimeAgo/index.ts

πŸ“¦ Imports

Name Source
AnyFn @vueuse/shared
Pausable @vueuse/shared
ComputedRef vue
MaybeRefOrGetter vue
ConfigurableScheduler ../_configurable
useIntervalFn @vueuse/shared
computed vue
toValue vue
useNow ../useNow

Variables & Constants

Name Type Kind Value Exported
DEFAULT_UNITS UseTimeAgoUnit<UseTimeAgoUnitNamesDef... const [ { max: 60000, value: 1000, name: 'second' }, { max: 2760000, value: 60000, ... βœ—
DEFAULT_MESSAGES UseTimeAgoMessages<UseTimeAgoUnitName... const { justNow: 'just now', past: n => /\d/.test(n) ?${n} ago: n, future: n =>... βœ—

Vue Composition API

Name Type Reactive Variables Composables
computed computed none none

Functions

useTimeAgo(time: MaybeRefOrGetter<Date | number | string>, options: UseTimeAgoOptions<false, UnitNames>): UseTimeAgoReturn<false>

Reactive time ago formatter.

See: https://vueuse.org/useTimeAgo

Tags: @__NO_SIDE_EFFECTS__

Raw JSDoc
/**
 * Reactive time ago formatter.
 *
 * @see https://vueuse.org/useTimeAgo
 *
 * @__NO_SIDE_EFFECTS__
 */
Code
export function useTimeAgo<UnitNames extends string = UseTimeAgoUnitNamesDefault>(time: MaybeRefOrGetter<Date | number | string>, options?: UseTimeAgoOptions<false, UnitNames>): UseTimeAgoReturn<false>

formatTimeAgo(from: Date, options: FormatTimeAgoOptions<UnitNames>, now: Date | number): string

Parameters:

  • from Date
  • options FormatTimeAgoOptions<UnitNames>
  • now Date | number

Returns: string

Calls:

  • n.toFixed
  • Math.abs
  • roundFn
  • getValue
  • applyFormat
  • formatter
  • formatter.replace
  • val.toString
  • fullDateFormatter
  • units.find
  • units.entries
  • format

Internal Comments:

// less than a minute

Code
export function formatTimeAgo<UnitNames extends string = UseTimeAgoUnitNamesDefault>(from: Date, options: FormatTimeAgoOptions<UnitNames> = {}, now: Date | number = Date.now()): string {
  const {
    max,
    messages = DEFAULT_MESSAGES as UseTimeAgoMessages<UnitNames>,
    fullDateFormatter = DEFAULT_FORMATTER,
    units = DEFAULT_UNITS as UseTimeAgoUnit<UnitNames>[],
    showSecond = false,
    rounding = 'round',
  } = options

  const roundFn = typeof rounding === 'number'
    ? (n: number) => +n.toFixed(rounding)
    : Math[rounding]

  const diff = +now - +from
  const absDiff = Math.abs(diff)

  function getValue(diff: number, unit: UseTimeAgoUnit<UnitNames>) {
    return roundFn(Math.abs(diff) / unit.value)
  }

  function format(diff: number, unit: UseTimeAgoUnit<UnitNames>) {
    const val = getValue(diff, unit)
    const past = diff > 0

    const str = applyFormat(unit.name as UnitNames, val, past)
    return applyFormat(past ? 'past' : 'future', str, past)
  }

  function applyFormat(name: UnitNames | keyof UseTimeAgoMessagesBuiltIn, val: number | string, isPast: boolean) {
    const formatter = messages[name]
    if (typeof formatter === 'function')
      return formatter(val as never, isPast)
    return formatter.replace('{0}', val.toString())
  }

  // less than a minute
  if (absDiff < 60000 && !showSecond)
    return messages.justNow

  if (typeof max === 'number' && absDiff > max)
    return fullDateFormatter(new Date(from))

  if (typeof max === 'string') {
    const unitMax = units.find(i => i.name === max)?.max
    if (unitMax && absDiff > unitMax)
      return fullDateFormatter(new Date(from))
  }

  for (const [idx, unit] of units.entries()) {
    const val = getValue(diff, unit)
    if (val <= 0 && units[idx - 1])
      return format(diff, units[idx - 1])
    if (absDiff < unit.max)
      return format(diff, unit)
  }

  return messages.invalid
}

past(n: string): string

Parameters:

  • n string

Returns: string

Code
n => /\d/.test(n) ? `${n} ago` : n

future(n: string): string

Parameters:

  • n string

Returns: string

Code
n => /\d/.test(n) ? `in ${n}` : n

month(n: number, past: boolean): string

Parameters:

  • n number
  • past boolean

Returns: string

Code
(n, past) => n === 1
    ? past
      ? 'last month'
      : 'next month'
    : `${n} month${n > 1 ? 's' : ''}`

year(n: number, past: boolean): string

Parameters:

  • n number
  • past boolean

Returns: string

Code
(n, past) => n === 1
    ? past
      ? 'last year'
      : 'next year'
    : `${n} year${n > 1 ? 's' : ''}`

day(n: number, past: boolean): string

Parameters:

  • n number
  • past boolean

Returns: string

Code
(n, past) => n === 1
    ? past
      ? 'yesterday'
      : 'tomorrow'
    : `${n} day${n > 1 ? 's' : ''}`

week(n: number, past: boolean): string

Parameters:

  • n number
  • past boolean

Returns: string

Code
(n, past) => n === 1
    ? past
      ? 'last week'
      : 'next week'
    : `${n} week${n > 1 ? 's' : ''}`

hour(n: number): string

Parameters:

  • n number

Returns: string

Code
n => `${n} hour${n > 1 ? 's' : ''}`

minute(n: number): string

Parameters:

  • n number

Returns: string

Code
n => `${n} minute${n > 1 ? 's' : ''}`

second(n: number): string

Parameters:

  • n number

Returns: string

Code
n => `${n} second${n > 1 ? 's' : ''}`

DEFAULT_FORMATTER(date: Date): string

Parameters:

  • date Date

Returns: string

Calls:

  • date.toISOString().slice
Code
function DEFAULT_FORMATTER(date: Date) {
  return date.toISOString().slice(0, 10)
}

Internal helpers

Declared inside another function in this file.

getValue(diff: number, unit: UseTimeAgoUnit<UnitNames>): number

Parameters:

  • diff number
  • unit UseTimeAgoUnit<UnitNames>

Returns: number

Calls:

  • roundFn
  • Math.abs
Code
function getValue(diff: number, unit: UseTimeAgoUnit<UnitNames>) {
    return roundFn(Math.abs(diff) / unit.value)
  }

format(diff: number, unit: UseTimeAgoUnit<UnitNames>): string

Parameters:

  • diff number
  • unit UseTimeAgoUnit<UnitNames>

Returns: string

Calls:

  • getValue
  • applyFormat
Code
function format(diff: number, unit: UseTimeAgoUnit<UnitNames>) {
    const val = getValue(diff, unit)
    const past = diff > 0

    const str = applyFormat(unit.name as UnitNames, val, past)
    return applyFormat(past ? 'past' : 'future', str, past)
  }

applyFormat(name: UnitNames | keyof UseTimeAgoMessagesBui…, val: number | string, isPast: boolean): string

Parameters:

  • name UnitNames | keyof UseTimeAgoMessagesBuiltIn
  • val number | string
  • isPast boolean

Returns: string

Calls:

  • formatter
  • formatter.replace
  • val.toString
Code
function applyFormat(name: UnitNames | keyof UseTimeAgoMessagesBuiltIn, val: number | string, isPast: boolean) {
    const formatter = messages[name]
    if (typeof formatter === 'function')
      return formatter(val as never, isPast)
    return formatter.replace('{0}', val.toString())
  }

Interfaces

UseTimeAgoMessagesBuiltIn

Interface Code
export interface UseTimeAgoMessagesBuiltIn {
  justNow: string
  past: string | UseTimeAgoFormatter<string>
  future: string | UseTimeAgoFormatter<string>
  invalid: string
}

Properties

Name Type Optional Description
justNow string βœ— not shown
past string \| UseTimeAgoFormatter<string> βœ— not shown
future string \| UseTimeAgoFormatter<string> βœ— not shown
invalid string βœ— not shown

FormatTimeAgoOptions<UnitNames extends string = UseTimeAgoUnitNamesDefault>

Interface Code
export interface FormatTimeAgoOptions<UnitNames extends string = UseTimeAgoUnitNamesDefault> {
  /**
   * Maximum unit (of diff in milliseconds) to display the full date instead of relative
   *
   * @default undefined
   */
  max?: UnitNames | number

  /**
   * Formatter for full date
   */
  fullDateFormatter?: (date: Date) => string

  /**
   * Messages for formatting the string
   */
  messages?: UseTimeAgoMessages<UnitNames>

  /**
   * Minimum display time unit (default is minute)
   *
   * @default false
   */
  showSecond?: boolean

  /**
   * Rounding method to apply.
   *
   * @default 'round'
   */
  rounding?: 'round' | 'ceil' | 'floor' | number

  /**
   * Custom units
   */
  units?: UseTimeAgoUnit<UnitNames>[]
}

Properties

Name Type Optional Description
max UnitNames \| number βœ“ not shown
fullDateFormatter (date: Date) => string βœ“ not shown
messages UseTimeAgoMessages<UnitNames> βœ“ not shown
showSecond boolean βœ“ not shown
rounding 'round' \| 'ceil' \| 'floor' \| number βœ“ not shown
units UseTimeAgoUnit<UnitNames>[] βœ“ not shown

UseTimeAgoOptions<Controls extends boolean, UnitNames extends string = UseTimeAgoUnitNamesDefault>

Interface Code
export interface UseTimeAgoOptions<Controls extends boolean, UnitNames extends string = UseTimeAgoUnitNamesDefault> extends FormatTimeAgoOptions<UnitNames>, ConfigurableScheduler {
  /**
   * Expose more controls
   *
   * @default false
   */
  controls?: Controls
}

Properties

Name Type Optional Description
controls Controls βœ“ not shown

UseTimeAgoUnit<Unit extends string = UseTimeAgoUnitNamesDefault>

Interface Code
export interface UseTimeAgoUnit<Unit extends string = UseTimeAgoUnitNamesDefault> {
  max: number
  value: number
  name: Unit
}

Properties

Name Type Optional Description
max number βœ— not shown
value number βœ— not shown
name Unit βœ— not shown

Type Aliases

UseTimeAgoFormatter<T = number>

type UseTimeAgoFormatter<T = number> = (value: T, isPast: boolean) => string;

UseTimeAgoUnitNamesDefault

type UseTimeAgoUnitNamesDefault = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year';

UseTimeAgoMessages<UnitNames extends string = UseTimeAgoUnitNamesDefault>

type UseTimeAgoMessages<UnitNames extends string = UseTimeAgoUnitNamesDefault> = UseTimeAgoMessagesBuiltIn
    & Record<UnitNames, string | UseTimeAgoFormatter<number>>;

UseTimeAgoReturn<Controls extends boolean = false>

type UseTimeAgoReturn<Controls extends boolean = false> = Controls extends true ? { timeAgo: ComputedRef<string> } & Pausable : ComputedRef<string>;

Generated by Syntax Scribe