Skip to content

Commit

Permalink
feat(useTimeAgo): add floor and ceil value calculation (#2543)
Browse files Browse the repository at this point in the history
Co-authored-by: Anthony Fu <anthonyfu117@hotmail.com>
  • Loading branch information
userquin and antfu committed Dec 16, 2022
1 parent 0c333bd commit a7dc61b
Showing 1 changed file with 11 additions and 2 deletions.
13 changes: 11 additions & 2 deletions packages/core/useTimeAgo/index.ts
Expand Up @@ -57,6 +57,13 @@ export interface UseTimeAgoOptions<Controls extends boolean> {
* @default false
*/
showSecond?: boolean

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

interface UseTimeAgoUnit {
Expand Down Expand Up @@ -124,9 +131,11 @@ export function useTimeAgo(time: MaybeComputedRef<Date | number | string>, optio
messages = DEFAULT_MESSAGES,
fullDateFormatter = DEFAULT_FORMATTER,
showSecond = false,
rounding = 'round',
} = options

const { abs, round } = Math
const { abs } = Math
const roundFn = Math[rounding]
const { now, ...controls } = useNow({ interval: updateInterval, controls: true })

function getTimeAgo(from: Date, now: Date) {
Expand Down Expand Up @@ -160,7 +169,7 @@ export function useTimeAgo(time: MaybeComputedRef<Date | number | string>, optio
}

function format(diff: number, unit: UseTimeAgoUnit) {
const val = round(abs(diff) / unit.value)
const val = roundFn(abs(diff) / unit.value)
const past = diff > 0

const str = applyFormat(unit.name, val, past)
Expand Down

0 comments on commit a7dc61b

Please sign in to comment.