skip to Main Content

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!

2

Answers


  1. fromNow function gives you the relative time so 45 days becomes a month(since it is close to a month). You can use the diff function to return the result in the format "X days ago" where X is the exact day number.

    const now = dayjs();
    const Cell = ({ value }) => {
      if (value) {
        const lastTouched = dayjs(value);
        const differenceInDays = now.diff(lastTouched, 'day');
        return `${differenceInDays} days ago`;
      }
      return null;
    };
    
    <script type="module">
    import dayjs from "https://esm.sh/[email protected]";
    const now = dayjs();
    const lastTouchedDate = dayjs().subtract(45, 'day'); // replace with actual
    const daysSinceLastTouched = (value) => {
      if (value) {
        const lastTouched = dayjs(value);
        const differenceInDays = now.diff(lastTouched, 'day');
        return `${differenceInDays} days ago`;
      }
      return null;
    };
    
    const result = daysSinceLastTouched(lastTouchedDate);
    console.log(result);
    </script>

    Note: Do not forget to add a logic for "day ago" and "days ago" to make it work for 1 day or so.

    Login or Signup to reply.
  2. 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
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search