console.log("Timestamp: " + data[0].timestamp)
>时间戳:1419860543788
var last_date = new Date(data[0].timestamp);
console.log(util.inspect(last_date));
>数字无效
如果我像这样创建Date对象
var last_date = new Date(1419860543788);
一切都很好,所以这里有什么?任何的想法? 我应该提一下,数据是从Mongoose查找方法返回的JSON对象(数据)
Blog.find({}).sort({timestamp: -1}).skip(0).limit(10).exec(function (err, data) {
答案 0 :(得分:2)
可能data[0].timestamp
是String
,如果您将其转换为Number
,则可以将其转换为Date
个实例:
var data = [{timestamp: '1419860543788'}], log = Helpers.log2Screen;
log(new Date(data[0].timestamp));
log(new Date(+data[0].timestamp)); //<= using + operator to convert to Number
<script src="http://kooiinc.github.io/JSHelpers/Helpers-min.js"></script>
答案 1 :(得分:1)
根据您的评论,data[0].timestamp
的值是一个字符串。
new Date(value);
Parameters
value
Integer value representing the number of milliseconds
since 1 January 1970 00:00:00 UTC (Unix Epoch).
现在,由于您传递的字符串不是整数/数字,因此它会执行此操作:
new Date(dateString);
Parameters
dateString
String value representing a date. The string should
be in a format recognized by the Date.parse() method
(IETF-compliant RFC 2822 timestamps and also a version
of ISO8601).
Date.parse()
了解日期,例如&#34; Wed,01 Jan 20xx 00:00:00 GMT&#34;和ISO日期,但不是时间戳。
如果你这样做:
new Date(parseInt(data[0].timestamp, 10));
您将获得有效的Date
对象。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date