|
| 1 | +import formatDistanceToNow from 'date-fns/formatDistanceToNow'; |
| 2 | +import differenceInMilliseconds from 'date-fns/differenceInMilliseconds'; |
| 3 | +import format from 'date-fns/format'; |
| 4 | +import isValid from 'date-fns/isValid'; |
| 5 | +import parseISO from 'date-fns/parseISO'; |
| 6 | +import i18next from 'i18next'; |
| 7 | + |
| 8 | +import { currentDateLocale } from '../i18n'; |
| 9 | + |
| 10 | +function parse(maybeDate) { |
| 11 | + const date = maybeDate instanceof Date ? maybeDate : parseISO(maybeDate); |
| 12 | + |
| 13 | + if (isValid(date)) { |
| 14 | + return date; |
| 15 | + } |
| 16 | + |
| 17 | + return null; |
| 18 | +} |
| 19 | + |
| 20 | +export default { |
| 21 | + distanceInWordsToNow(date) { |
| 22 | + const parsed = parse(date); |
| 23 | + |
| 24 | + if (parsed) { |
| 25 | + const now = new Date(); |
| 26 | + const diffInMs = differenceInMilliseconds(now, parsed); |
| 27 | + |
| 28 | + if (Math.abs(diffInMs < 10000)) { |
| 29 | + return i18next.t('formatDate.JustNow'); |
| 30 | + } else if (diffInMs < 20000) { |
| 31 | + return i18next.t('formatDate.15Seconds'); |
| 32 | + } else if (diffInMs < 30000) { |
| 33 | + return i18next.t('formatDate.25Seconds'); |
| 34 | + } else if (diffInMs < 46000) { |
| 35 | + return i18next.t('formatDate.35Seconds'); |
| 36 | + } |
| 37 | + |
| 38 | + const timeAgo = formatDistanceToNow(parsed, { |
| 39 | + includeSeconds: false, |
| 40 | + locale: currentDateLocale() |
| 41 | + }); |
| 42 | + return i18next.t('formatDate.Ago', { timeAgo }); |
| 43 | + } |
| 44 | + |
| 45 | + return ''; |
| 46 | + }, |
| 47 | + format(date, { showTime = true } = {}) { |
| 48 | + const parsed = parse(date); |
| 49 | + const formatType = showTime ? 'PPpp' : 'PP'; |
| 50 | + |
| 51 | + if (parsed) { |
| 52 | + return format(parsed, formatType, { locale: currentDateLocale() }); |
| 53 | + } |
| 54 | + |
| 55 | + return ''; |
| 56 | + } |
| 57 | +}; |
0 commit comments