简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM