[英]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我想知道如何使用库或纯 JS 转换这样的日期
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.但不正确,因为我需要 11 个以上的数字和 +00。
When you use UTCDate() , you need have a full date to get all items:当您使用UTCDate()时,您需要一个完整的日期来获取所有项目:
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 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 2021-03-05 13:05:36.51605+00
I hope could help.我希望能有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.