Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(useTimeAgo): add floor and ceil value calculation #2543

Merged
merged 2 commits into from Dec 16, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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