SWS-5007 / My-Experience

13 stars 0 forks source link

The way to show the relative timestamp description in React. #1

Closed SWS-5007 closed 1 year ago

SWS-5007 commented 1 year ago

Hi. Libraries like date-fns have some useful utility functions for parsing and formatting dates. Please check codebase below.

import React from 'react'
import { parseISO, formatDistanceToNow } from 'date-fns'

export const TimeAgo = ({ timestamp }) => {
  let timeAgo = ''
  if (timestamp) {
    const date = parseISO(timestamp)
    const timePeriod = formatDistanceToNow(date)
    timeAgo = `${timePeriod} ago`
  }

  return (
    <span title={timestamp}>
      &nbsp; <i>{timeAgo}</i>
    </span>
  )
}

Please give me great feedback. Thanks!