我正在尝试构建一个 javascript 对象数组,使用 date.js 解析日期,然后使用 date.js 比较方法对该对象进行排序。这是我整理的一些代码来演示我的两个问题。
问题 1:如何忽略 date.js 无法解析的日期并发出警告?问题 2:如何按这些日期对对象数组进行排序?(有或没有 date.js)
我的直觉告诉我,我做错了,还有更好的方法。想法?
<script type="text/javascript" src="depend/date.js"></script>
<script type="text/javascript">
var timedata = ["tomorrow", "today", "next thursday", "2012-08-02T04:00:00.000Z"]; // test data
var myArrayOfObjects = [];
//Iterate through the timedata array
for(var row = 0; row < timedata.length; row++){
var cleanrow = true;
// Here is the first problem, on the 2012-08-02T04:00:00.000Z string can't be parsed (Date.parse(timestr) returns 0)
// even though it was previously created with .toISOString method below as a test
// Error: Ignoring row 3, could not parse this date: 2012-08-02T04:00:00.000Z
if (Date.parse(timedata[row])){
time = Date.parse(timedata[row]);
isoTime = time.toISOString();
}else{
console.log("Ignoring row " + row + ", could not parse this date: " + timedata[row]);
cleanrow = false;
}
var xdata = "dummytestdata";
var weight = "dummytestdata";
if(cleanrow) {
myArrayOfObjects.push({x: xdata, xytime: isoTime, weight: weight});
}
}
// Here is the second problem.
// Error: TypeError: Date.parse(a.xytime) is null
myArrayOfObjects = myArrayOfObjects.sort(function(a,b){ return Date.parse(a.xytime).compareTo(Date.parse(b.xytime)); });
// Show that the objects are sorted by dates
for(var row = 0; row < myArrayOfObjects.length; row++) {
console.log(myArrayOfObjects[row].xytime);
}
</script>