Search code examples
javascriptreactjssortingdatedayjs

Using .fromNow() to display just the days passed instead of less accurate terms (months, year, etc.)


I'm working on setting up a table that shows long it's been since something has last been touched. I was to only show how many days have passed, and not have the cell reduce to something less accurate like months, to make comparison faster. For example, if something has been untouched for 45 days, right now JS is reducing that down to 1 month, when I want it to instead display 45 days

Right now, I'm currently using this to display time past, and I've seen solutions to change how the time may be represented, but only how to change the output, not reduce months to days

Cell: ({ value }) => {
    return value ? dayjs(new Date(now - value)).fromNow() : null;
}

Any help is greatly appreciated!


Solution

  • An easy workaround is to use the .diff function like so :

    const fromDaysAgo = (date) => { 
      if (!date) return null //early return
      const now = dayjs() // now
      const diffDays = now.diff(dayjs(date), 'day') // difference in days
      return ’${diffDays} days ago‘ //custom text
    }