Skip to content

Commit

Permalink
feat(date): 新增 formatDistancePlus
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Feb 17, 2023
1 parent c8227b2 commit 668ccd5
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 0 deletions.
36 changes: 36 additions & 0 deletions src/date/formatDistancePlus.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { addDays, addYears, subDays, subYears } from 'date-fns/esm'
import { formatDistancePlus } from './formatDistancePlus'

describe('formatDistancePlus', () => {
test('前', () => {
expect(formatDistancePlus(subDays(new Date(), 1))).toBe('1天前')
expect(formatDistancePlus(subDays(new Date(), 1.5))).toBe('1天前')
expect(formatDistancePlus(subYears(new Date(), 10))).toBe('10年前')

expect(
formatDistancePlus(subDays(new Date(), 1), addDays(new Date(), 2)),
).toBe('3天前')
expect(
formatDistancePlus(subDays(new Date(), 1.5), addDays(new Date(), 2)),
).toBe('3天前')
expect(
formatDistancePlus(subYears(new Date(), 10), addYears(new Date(), 3)),
).toBe('13年前')
})

test('后', () => {
expect(formatDistancePlus(addDays(new Date(), 1))).toBe('1天后')
expect(formatDistancePlus(addDays(new Date(), 1.5))).toBe('1天后')
expect(formatDistancePlus(addYears(new Date(), 10))).toBe('10年后')

expect(
formatDistancePlus(addDays(new Date(), 1), subDays(new Date(), 1)),
).toBe('2天后')
expect(
formatDistancePlus(addDays(new Date(), 1.5), subDays(new Date(), 1)),
).toBe('2天后')
expect(
formatDistancePlus(addYears(new Date(), 10), subYears(new Date(), 10)),
).toBe('20年后')
})
})
19 changes: 19 additions & 0 deletions src/date/formatDistancePlus.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { formatDistanceStrict, isBefore } from 'date-fns/esm'
import { zhCN } from 'date-fns/esm/locale'

/**
* 将时间转化为 `xxx前/后` 表示。
*
* @param date 时间
* @param baseDate 基准时间(默认当前时间)
*/
export function formatDistancePlus(
date: Date,
baseDate: Date = new Date(),
): string {
const suffix = isBefore(date, baseDate) ? '前' : '后'
const distance = formatDistanceStrict(date, baseDate, {
locale: zhCN,
}).replace(/\s+/g, '')
return `${distance}${suffix}`
}
1 change: 1 addition & 0 deletions src/date/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,7 @@ export {
export * from './anyToDate'
export * from './formatDate'
export * from './formatDistanceAgo'
export * from './formatDistancePlus'
export * from './intervalToRestrictiveDuration'
export * from './ms'
export * from './numeralDayToChineseDay'
Expand Down

0 comments on commit 668ccd5

Please sign in to comment.