0

I'm running an application where a timestamp is generated whenever a column from the backend is updated. On the frontend I'm able to read that timestamp, however, I'm struggling to format it.

The simplest thing I tried to do was to apply

portal.manager.updated_at.toISOString().substring(0, 10)

but I got: ".toISOString is not a function".

Also, where should I format this value? In the backend or in the frontend? This value is being generated by TypeORM with SQLite.

Column Definition:

{
  name: 'updated_at',
  type: 'timestamp',
  default: 'now()',
},

At the model:

@UpdateDateColumn()
updated_at: Date;

In the Frontend:

type Portal = {
  name: string;
  manager: {
    updated_at: Date;
  };
}
export default function Portals() {
return (
  <div>
    <h1>{portal.manager.updated_at}</h1>
  </div>
);

Thanks a lot!

Rafael
  • 63
  • 6

3 Answers3

1

You should format on the client side.

If you are fetching data from rest api my guessing is that your date is a string, even after parsing the response. You need to wrap it with new Date(updated_at)

UnnamedXAer
  • 159
  • 6
0

moment.js and date-fns are two popular date utility libraries. Choose any one of your liking and use it to parse the date (updated_at)

ZealousWeb
  • 1,029
  • 1
  • 6
  • 8
0

The straightforward answer to my question led to:

type Portal = {
  name: string;
  manager: {
    updated_at: Date;
  };
}
export default function Portals() {
return (
  <div>
    <h1>{new Date(portal.manager.updated_at).substring(0, 10)}</h1>
  </div>
);

However, if you want (and that's my case) to really format your date, rather than just trimming a part of it this is the solution with date-fns

import format from 'date-fns/format';

type Portal = {
  name: string;
  manager: {
    updated_at: Date;
  };
}

function formatDate(date: Date) {
  const formattedDate = format(new Date(date), 'dd/MM/yyyy');
  return formattedDate;
}

export default function Portals() {
return (
  <div>
    <h1>{formatDate(portal.manager.updated_at)}</h1>
  </div>
);

Rafael
  • 63
  • 6