[英]Converting data javascript
In a for loop, I want to get different dates for every item. 在for循环中,我想为每个项目获取不同的日期。 I had implemented the following and it was working fine:
我实现了以下内容,并且运行良好:
//This retrieves the right dates:
result.date = offer.get("createdAt");
result.updated = exchange.get("updatedAt");
result.expiration = exchange.get("expirationDate");
I was getting: 我得到:
2017-09-01T20:33:35.245Z
2017-08-01T19:07:15.510Z
2017-07-28T19:43:11.590Z
As I want to convert to date format and get only month, date, year and time, I implement this: 由于我想转换为日期格式并仅获取月份,日期,年份和时间,因此我实现了这一点:
//This brings the same date every time;
var date = Date(offer.get("createdAt"));
result.date = date.substr(4, 17);
result.shortDate = result.date.substr(4, 11);
var expiration = Date(exchange.get("expirationDate"));
result.expiration = expiration.substr(4, 11);
var updated = Date(exchange.get("updatedAt"));
result.updated = updated.substr(4, 11);
But it keeps bringing the same date for every element: 但是它总是为每个元素带来相同的日期:
Sep 02 2017 18:08
Sep 02 2017 18:08 (this should be a different date)
Sep 02 2017 18:08 (this should be a different date)
I don't what I am missing! 我不是我所想念的! Thanks a lot.
非常感谢。
Okay, use the following code instead: 好的,改为使用以下代码:
var date = new Date(offer.get("createdAt"));
result.date = date.toString().substr(4, 17);
result.shortDate = result.date.substr(4, 11);
var expiration = new Date(exchange.get("expirationDate"));
result.expiration = expiration.toString().substr(4, 11);
var updated = new Date(exchange.get("updatedAt"));
result.updated = updated.toString().substr(4, 11);
So, the issue is you are not using Date() with the new keyword. 因此,问题在于您没有将new()与Date()一起使用。
Use the new
keyword before Date()
, without it, you're just creating today's date, then convert them to strings in order to use substr
with them : 在
Date()
之前使用new
关键字,如果没有它,您只是在创建今天的日期,然后将它们转换为字符串,以便对它们使用substr
:
var result = {}; var date = new Date("2017-09-01T20:33:35.245Z").toString(); result.date = date.substr(4, 17); result.shortDate = result.date.substr(4, 11); var expiration = new Date("2017-08-01T19:07:15.510Z").toString(); result.expiration = expiration.substr(4, 11); var updated = new Date("2017-07-28T19:43:11.590Z").toString(); result.updated = updated.substr(4, 11); console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.