I'm currently working on creating a JavaScript array of objects, utilizing date.js to parse dates, and then sorting that array using date.js compare methods. Below is a snippet of code that highlights the two issues I am facing.
Issue 1: How can I handle dates that cannot be parsed by date.js and provide a warning for them? Issue 2: What is the best way to sort an array of objects based on these dates? (with or without date.js)
I have a feeling that my approach may not be optimal, so I would appreciate any suggestions or ideas.
<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"]; // sample data
var myArrayOfObjects = [];
//Iterating through the timedata array
for(var row = 0; row < timedata.length; row++){
var cleanrow = true;
// First issue, unable to parse the string "2012-08-02T04:00:00.000Z" with Date.parse(timestr) returning 0
// even though it was initially created using the .toISOString method 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});
}
}
// Second issue
// Error: TypeError: Date.parse(a.xytime) is null
myArrayOfObjects = myArrayOfObjects.sort(function(a,b){ return Date.parse(a.xytime).compareTo(Date.parse(b.xytime)); });
// Displaying the sorted objects by dates
for(var row = 0; row < myArrayOfObjects.length; row++) {
console.log(myArrayOfObjects[row].xytime);
}
</script>