useTimeAgo
A React Hook that helps to format a date to a human-readable time ago string. It will automatically update the time ago string every 30 seconds by default.
Demo
Usage
See API for more details.
Source
Click links below to view source on GitHub.
API
const timeAgo = useTimeAgo(dateLike, options)
const { timeAgo, ...pausable } = useTimeAgo(dateLike, { controls: true, ...otherOptions })
DateLike
// like new Date(), 1_612_137_600_000, '2021-01-01', undefined, null
export type DateLike = Date | number | string | undefined | null
Options
export type FormatTimeAgoOptions<UnitNames extends string = TimeAgoUnitNamesDefault> = {
/**
* Maximum unit (of diff in milliseconds) to display the full date instead of relative
*
* @defaultValue undefined
*/
max?: UnitNames | number
/**
* Formatter for full date
*/
fullDateFormatter?: TimeAgeFullDateFormatter
/**
* Messages for formatting the string
*/
messages?: TimeAgoMessages<UnitNames>
/**
* Minimum display time unit (default is minute)
*
* @defaultValue false
*/
showSecond?: boolean
/**
* Rounding method to apply.
*
* @defaultValue 'round'
*/
rounding?: 'round' | 'ceil' | 'floor' | number
/**
* Custom units
*/
units?: TimeAgoUnit<UnitNames>[]
}
export interface UseTimeAgoOptions<Controls extends boolean, UnitNames extends string = TimeAgoUnitNamesDefault>
extends FormatTimeAgoOptions<UnitNames> {
/**
* Expose more controls
*
* @defaultValue false
*/
controls?: Controls
/**
* Intervals to update, set 0 to disable auto update
*
* @defaultValue 30_000
*/
updateInterval?: number
}
Returns
Retuerns contain Pausable instance that can be paused, resumed.
See Pausable for more details.
export type UseTimeAgoReturns<Controls extends boolean = false> = Controls extends true
? { timeAgo: string } & Pausable
: string