How in javascript to convert a date to a specific format

I would like to know how can I convert with a library or pure JS a date like this

Fri Mar 05 2021 13:51:35 GMT+0000 (Coordinated Universal Time)

to this format

2021-03-05 13:51:35.829058+00

As asked in comments what I was trying to achieve is to convert the shared date to specific format I tried the following stuff

1) const t = createdAt
      .toISOString()
      .replace('T', ' ')
      .replace('Z', '');
2) Using date-fns
format(addMinutes(date, date.getTimezoneOffset()), 'yyyy-MM-dd HH:mm:ss');

The result of those tries is like

2021-03-05 14:44:11

But is not correct as I need after 11 more numbers and +00.

Answer

When you use UTCDate(), you need have a full date to get all items:

function pad(e){ return (e.toString().length<2?'0'+e:e); }

function ShowData(data){ var d = new Date(data); return d.getFullYear()+'-'+pad(d.getMonth()+1) +'-'+ pad(d.getDate())+' '+pad(d.getHours())+':'+pad(d.getMinutes())+':'+pad(d.getSeconds())+'.'+pad(d.getMilliseconds())+pad(d.getUTCDate())+"+00"; }

When you use your example:

ShowData('Fri Mar 05 2021 13:51:35 GMT+0000');

Then you got

2021-03-05 10:51:35.0005+00

When we use a full date form:

ShowData(new Date());

Then you got

2021-03-05 13:05:36.51605+00

I hope could help.

Leave a Reply

Your email address will not be published. Required fields are marked *