I have the following code:
//var data is an array of objects
var dateRegex = /(\d{4})-(\d{2})-(\d{2})T(\d{2})\:(\d{2})\:(\d{2})/;
var dataDateFields = [];
$.each(data[0], function (name, value) {
if (jQuery.type(value) === "string") {
if (value.match(dateRegex)) {
dataDateFields.push(name);
}
}
});
if (dataDateFields.length > 0) {
$.each(data, function (e) {
$.each(this, function(name, value) {
if (jQuery.inArray(name, dataDateFields) !== -1) {
var tempDate = new Date(value);
this.value = tempDate;
}
});
});
}
What this code does is it gets data through to it, which is an array of objects from a table in a db. It then searches through the fields of the first object, and gets the name of the column(s) that have data in them that looks like a datetime field. It saves the name of these fields in an array. It then goes through every row in the data, and each column that has a datetime field name, it converts that data from a string to a Date type.
The problem I have is last part of the code. The bit of code:
if (jQuery.inArray(name, dataDateFields) !== -1) {
var tempDate = new Date(value);
this.value = tempDate;
}
The code enters the if statement, it correctly populates tempDate with a Date variable from the supplied string. I would then think that
this.value = tempDate;
would then overwrite the previously stored datetime string with the new Date. But it doesn't. When I look at the data after it's all been looped through, the fields which have datetime strings are still the same, it hasn't populated those fields with the converted Date data. ps. tempDate when checked is always properly converted to a Date type and in the right format.
Anybody got any idea how I can achieve this? Also, is there any simpler way to do what I'm doing? This code works on the assumption that I don't know what data will be passed to me, or what fields it will contain - I only know that it may contain datetime fields in string format, so, for the purposes of calculations done later on, I need to check each field, see if it looks like a date, then convert all of the strings with that field's name to Date types.