index.tsx raw

   1  import dayjs from 'dayjs'
   2  import { useTranslation } from 'react-i18next'
   3  
   4  export function FormattedTimestamp({
   5    timestamp,
   6    short = false,
   7    className
   8  }: {
   9    timestamp: number
  10    short?: boolean
  11    className?: string
  12  }) {
  13    return (
  14      <span className={className}>
  15        <FormattedTimestampContent timestamp={timestamp} short={short} />
  16      </span>
  17    )
  18  }
  19  
  20  function FormattedTimestampContent({
  21    timestamp,
  22    short = false
  23  }: {
  24    timestamp: number
  25    short?: boolean
  26  }) {
  27    const { t } = useTranslation()
  28    const time = dayjs(timestamp * 1000)
  29    const now = dayjs()
  30  
  31    const diffMonth = now.diff(time, 'month')
  32    if (diffMonth >= 2) {
  33      return t('date', { timestamp: time.valueOf() })
  34    }
  35  
  36    const diffDay = now.diff(time, 'day')
  37    if (diffDay >= 1) {
  38      return short ? t('n d', { n: diffDay }) : t('day ago', { count: diffDay })
  39    }
  40  
  41    const diffHour = now.diff(time, 'hour')
  42    if (diffHour >= 1) {
  43      return short ? t('n h', { n: diffHour }) : t('hour ago', { count: diffHour })
  44    }
  45  
  46    const diffMinute = now.diff(time, 'minute')
  47    if (diffMinute >= 1) {
  48      return short ? t('n m', { n: diffMinute }) : t('minute ago', { count: diffMinute })
  49    }
  50  
  51    return t('just now')
  52  }
  53