Skip to content

Commit

Permalink
feat(date): 新增 formatDistanceAgo
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Oct 10, 2020
1 parent 725cd09 commit 2715dee
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/date/__snapshots__/formatDistanceAgo.test.ts.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`formatDistanceAgo 表现正常: 分 1`] = `"4分钟前"`;

exports[`formatDistanceAgo 表现正常: 天 1`] = `"10天前"`;

exports[`formatDistanceAgo 表现正常: 年 1`] = `"6年前"`;

exports[`formatDistanceAgo 表现正常: 时 1`] = `"1小时前"`;

exports[`formatDistanceAgo 表现正常: 月 1`] = `"3个月前"`;

exports[`formatDistanceAgo 表现正常: 秒 1`] = `"20秒前"`;
20 changes: 20 additions & 0 deletions src/date/formatDistanceAgo.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { formatDistanceAgo } from './formatDistanceAgo'
import {
subDays,
subHours,
subMinutes,
subMonths,
subSeconds,
subYears,
} from 'date-fns/esm'

describe('formatDistanceAgo', () => {
test('表现正常', () => {
expect(formatDistanceAgo(subYears(new Date(), 6))).toMatchSnapshot('年')
expect(formatDistanceAgo(subMonths(new Date(), 3))).toMatchSnapshot('月')
expect(formatDistanceAgo(subDays(new Date(), 10))).toMatchSnapshot('天')
expect(formatDistanceAgo(subHours(new Date(), 1))).toMatchSnapshot('时')
expect(formatDistanceAgo(subMinutes(new Date(), 4))).toMatchSnapshot('分')
expect(formatDistanceAgo(subSeconds(new Date(), 20))).toMatchSnapshot('秒')
})
})
14 changes: 14 additions & 0 deletions src/date/formatDistanceAgo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { formatDistanceToNowStrict } from 'date-fns/esm'
import { zhCN } from 'date-fns/esm/locale'

/**
* 将时间转化为 `xxx前` 表示。
*
* @param date 时间
*/
export function formatDistanceAgo(date: number | Date): string {
const distance = formatDistanceToNowStrict(date, {
locale: zhCN,
})
return `${distance.replace(/\s+/g, '')}前`
}
1 change: 1 addition & 0 deletions src/date/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,7 @@ export {
// @index(['./**/*.ts', '!./**/*.test.*'], f => `export * from '${f.path}'`)
export * from './anyToDate'
export * from './formatDate'
export * from './formatDistanceAgo'
export * from './intervalToRestrictiveDuration'
export * from './numeralDayToChineseDay'
// @endindex

0 comments on commit 2715dee

Please sign in to comment.