[英]How to change date format using JavaScript
Apologies if duplicate 道歉,如果重复
I have a date in Mon May 29 2017 12:36:49 GMT+0000
and I want to convert it into 2017-05-01T19:04:18Z
How can i do that using JavaScript. 我有一个日期为
Mon May 29 2017 12:36:49 GMT+0000
,我想将其转换为2017-05-01T19:04:18Z
如何使用JavaScript做到这一点。
Here is my code 这是我的代码
var targetDate = new Date();
targetDate.setDate(targetDate.getDate() - 5);
console.log("targetDate is "+targetDate);
I am getting output like targetDate is Mon May 29 2017 12:36:49 GMT+0000
but I want it in 2017-05-01T19:04:18Z
format 我得到的输出像
targetDate is Mon May 29 2017 12:36:49 GMT+0000
但我想要2017-05-01T19:04:18Z
格式
Any help appreciated, Thanks in advance 任何帮助表示赞赏,在此先感谢
This is not the best practice, but still putting it here for your reference: 这不是最佳做法,但仍将其放在此处供您参考:
Date.prototype.toString = function() {
return `${this.getFullYear()}-${this.getMonth() + 1}-${this.getDate()}T${this.getHours()}:${this.getMinutes()}:${this.getSeconds()}`;
}
d = new Date()
2017-6-3T18:39:34
function addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
var targetDate = new Date();
targetDate.setDate(targetDate.getDate() - 5);
var newTime = targetDate.getFullYear()+"-"+addZero(targetDate.getMonth())+"-"+addZero(targetDate.getDate())+" "+addZero(targetDate.getHours())+":"+addZero(targetDate.getMinutes())+":"+addZero(targetDate.getSeconds());
alert(newTime);
Are you looking for JSON encoded date? 您在寻找JSON编码日期吗?
You can parse that with the JSON serializer: 您可以使用JSON序列化器对此进行解析:
console.log("targetDate is "+ JSON.stringify(targetDate));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.